shell编程参考

语言特性

逻辑控制

if [ expression ]; then
    statements
fi

if [expression1 ]; then
    statements1
elif [ expression2 ]; then
    statements2
else
    statements3
fi

var=0
while [ $var -lt 10 ]; do
    var=$(($var + 1))
done

for ((i=0; i<10; i++)); do
    echo $i
done

for name in $(cat userlist); do
    echo $name
done

case $option in
    a) echo "option -a";;
    b) echo "option -b";;
    *) echo "unknown option";;
esac

条件测试

预定义变量

整数运算

let a++       <=>  ((a=a+1))
let a+=5      <=>  ((a+=5))
let a=a**2    <=>  ((a=a**2))
let a%=7      <=>  ((a%=7))

浮点数运算

printf "%.3f\n" $(echo "1/13" | bc -l)
echo "1 13" | awk '{printf("%.3f\n", $1/$2)}'

生成随机数

echo | awk 'BEGIN{srand()}END{for(i=0;i<10;i++) printf("%d\n", 256*rand());}'

字符串操作

字符串匹配截取

url="ftp://anoymouns:ftp@mirror.lzu.edu.cn/software/scim-1.4.7.tar.gz"
protocol: ${url%%:*}                      ==> ftp
domain: tmp=${url##*@}; ${tmp%%/*}        ==> mirror.lzu.edn.cn
path: tmp=${url##*@}; ${tmp%/*}           ==> mirror.lzu.edu.cn/software
basename: ${url##*/}                      ==> scim-1.4.7.tar.gz
Table of Contents