学习: https://www.learnshell.org/

变量赋值, = 两边不能有空格

$ 用来引用变量:

  1. a=world
  2. echo hello $a
  1. ```bash
  2. echo -e "Files:\n`ls`"
  3. # or
  4. echo -e "Files:\n$(ls)"

参数操作

$x 第几个参数,script是第0个
$# 参数数量,包括script
$@ 所有参数,空格分隔的string

数组

(a b c)
空格分隔

a=(a b 123)
echo ${a[@]} # 得到所有元素
echo ${#a[@]} # 得到元素数量

数学运算

$(())

A=3
B=$((100 * $A + 5))

if

NAME="George"
if [ "$NAME" = "John" ]; then
  echo "John Lennon"
elif [ "$NAME" = "George" ]; then
  echo "George Harrison"
else
  echo "This leaves us with Paul and Ringo"
fi

case

mycase=1
case $mycase in
    1) echo "You selected bash";;
    2) echo "You selected perl";;
    3) echo "You selected phyton";;
    4) echo "You selected c++";;
    5) exit
esac

for

# loop on array member
NAMES=(Joe Jenny Sara Tony)
for N in ${NAMES[@]} ; do
  echo "My name is $N"
done

# loop on command output results
for f in $( ls prog.sh /etc/localtime ) ; do
  echo "File is: $f"
done

while

COUNT=4
while [ $COUNT -gt 0 ]; do
  echo "Value of count is: $COUNT"
  COUNT=$(($COUNT - 1))
done

function

function adder {
  echo "$(($1 + $2))"
}

特殊变量

  • $0 运行的script名称
  • $n 第n个变量
  • $# 参数数量(函数或者script)
  • $@ , $* 所有的参数
  • $? 上一个命令的exit status
  • $$ 当前的进程id

$@$* 的细微差别

function func {
    echo "--- \"\$*\""
    for ARG in "$*"
    do
        echo $ARG
    done

    echo "--- \"\$@\""
    for ARG in "$@"
    do
        echo $ARG
    done
}
func We are argument

output:

--- "$*"
We are argument
--- "$@"
We
are
argument

文件相关测试

测试文件存在:

if [ -e 'filename' ]; then
    #...
fi

测试目录存在:

if [ -d 'filename' ]; then
    #...
fi

测试文件有读的权限: -r

Pipe

| : 标准化输入输出,上一个命令的输出作为下一个命令的输入:

ls / | head

如果需要处理stderr道stdout,考虑: 2>$1 | ,可以简写为 |&