Shell Scripts

1 什么是 shell scripts

shell scripts 是利用 shell 功能所写的程序。 shell script 在系统管理方面是一个很好的工具,但是在数值运算方面就不够好了,速度慢,占用资源多。

2 简单的练习

2.1 对话

2.2 日期

2.3 运算

3 默认变量

/path/to/scriptname  opt1  opt2  opt3
$0                   $1    $2    $3

$# = 参数个数
$@ = "$1" "$2" "$3" "$4"
$* = "$1 $2 $3 $4"

4 script 运行方式的差异

  • 直接运行或用 bash 运行,运行结束变量消亡。
  • 用 source 运行,运行结束变量存续。

5 控制语句

5.1 判断

判断存在与否

  • test -e name 该东西是否存在?
  • test -f name 该文档是否存在?
  • test -d name 该目录是否存在?

判断两个整数

  • test n1 -eq n2 相等?
  • test n1 -ne n2 不等?
  • test n1 -gt n2 大于?
  • test n1 -lt n2 小于?
  • test n1 -ge n2 大于等于?
  • test n1 -le n2 小于等于?

判断字符串

  • test -z string 为空?
  • test -n string 非空?
  • test str1 = str2 相等?
  • test str1 != str2 不等?

多重判断

  • test -r file -a -w file
  • test -r file -o -w file
  • test ! -x file

[ str1 == str2 ] 等价于 test str1 = str2在 bash 当中使用一个等号与两个等号的结果是一样的!使用一个等号时注意等号两边有空格,否则被视为赋值!

5.2 条件语句

if 版条件语句

if [ bool_1 ]; then
    do_something
elif [ bool_2 ]; then
    do_something
else
    do_something
fi

case 版条件语句

case $var in
    "var_1")
        do_something
        ;;
    "var_2")
        do_something
        ;;
    *)
        do_something
        ;;
esac

5.3 循环语句

while 版循环语句

while [ condition ]
do
    do_something
done

until 版循环语句

until [ condition ]
do
    do_something
done

for 版循环语句

for var in con1 con2 con3 ...
do
    do_something
done

for (( i=1; i<=$nu; i=i+1 ))
do
    do_something
done

6 函数

function fname() {
    do_something
}

7 调试

打印输出。