Shell(2)

传递参数

运行脚本时后续可以用空格传递若干参数

变量 说明
$0 当前文件名
$1~$n 第1~n个参数
$# 参数数量
$* 所有参数,不可迭代
$@ 所有参数,可迭代

流程控制

for

  • 对于可迭代对象使用
    for var in iterable; do
    command
    done

    for var in item1 item2 item3 itemN; do
    command
    done

while

  • 满足循环条件时执行语句
    while condition; do
    command
    done

    int=1
    while ((int <= 5)); do
    echo $int
    ((int++))
    done

until

  • 不满足条件时执行语句
    int=1
    until [ ! $a -lt 10 ]; do
    echo $a
    a=`expr $a + 1`
    done

if-else

  • 分支控制语句
    if condition; then
    command
    elif condition; then
    command
    else
    command
    fi

case

  • 分支控制语句
  • 需要使用case esac包裹
  • ;;代表break操作
  • condition)代表分支,可以同时有多个使用|隔开例如,1|2|3)*代表剩余的结果
    case $var in
    1) echo $((var-1))
    ;;
    2) echo $((var-2))
    ;;
    3) echo $((var-3))
    ;;
    *) echo $((var))
    esac

break & continue

  • 同C语言,在跳出循环时使用

函数

  • 函数定义时可以省略function
  • 函数如果需要返回值必须是0~255,否则返回函数体内最后一句指令的结果
    [ function ] funname [()]
    {

    action;

    [return int;]

    }
  • 在函数外使用$?来获得函数返回值
  • 如果给函数传递参数,在函数内的操作同传递参数,尤其注意${10}
    funWithParam(){
    echo "第一个参数为 $1 !"
    echo "第二个参数为 $2 !"
    echo "第十个参数为 $10 !"
    echo "第十个参数为 ${10} !"
    echo "第十一个参数为 ${11} !"
    echo "参数总数有 $# 个!"
    echo "作为一个字符串输出所有参数 $* !"
    }

    funWithParam 1 2 3 4 5 6 7 8 9 34 73

重定向

重定向命令

命令 说明
command > file 将命令的输出重定向到file中(覆盖)
command < file 将命令的输入重定向到file中
command >> file 将命令的输出重定向到file中(追加)
n>file 将文件描述符n的文件重定向到file中(覆盖)
n>>file 将文件描述符n的文件重定向到file中(追加)
n>&m 将输出文件n与m合并
n<&m 将输入文件n与m合并

文件描述符

文件描述符 说明
0 stdin
1 stdout
2 stderr

常用操作

# hello.txt:
# test
echo "hello" > hello.txt
# hello.txt:
# hello

# hello.txt:
# test
echo "hello" >> hello.txt
# hello.txt:
# test
# hello

echo "hello" > hello.txt
# 等同于 echo "hello" 1>hello.txt

# 如果希望传递stderr到hello.txt中
echo "hello" 2>hello.txt

# 如果希望同时传递stdout与stderr
echo "hello" > hello.txt 2>&1
# echo "hello" >> hello.txt 2>&1

屏蔽

  • /dev/null是一个特殊文件,写入的内容会被丢弃,读出的内容为空
  • 可以重定向到此文件来屏蔽输出
    command > /dev/null
    # 屏蔽stdout

    command 2>/dev/null
    # 屏蔽stderr

    command > /dev/null 2>&1
    # 屏蔽stdout和stderr