shell 流程控制
分支语句
- if else-if else
#! /bin/bash a=10 b=20 if [ $a == $b ] #此处用[[]]也是可以的,shell标准手册中推荐使用 [[]] then echo "a 等于 b" elif [ $a -gt $b ] then echo "a 大于 b" elif [ $a -lt $b ] then echo "a 小于 b" else echo "没有符合的条件" fi
- case
#! /bin/bash a=4 case $a in 1) echo 'a is 1' ;; 2) echo 'a is 2' ;; 3|4) echo 'a is 3 or 4' ;; *) echo 'a is others' ;; esac
循环语句
- for 循环
- while 循环
#! /bin/bash i=1 while [ $i -le 5 ] do echo $i let "i++" done
- until 循环
#! /bin/bash a=0 until [ ! $a -lt 10 ] do echo $a a=`expr $a + 1` done
跳出循环
- break
- continue
总结
- case 语句中的 ;; 是不能省略的,不会出现C代码中的,不加break,跳到下一个case中继续执行的写法
- break、continue 只会用于跳出循环
拓展
- Conditional expressions are used by the [[ compound command and the test and [ builtin commands.
- The shell allows arithmetic expressions to be evaluated, as one of the shell expansions or by using the (( compound command, the let builtin, or the -i option to the declare builtin
$ cat demo.sh #! /bin/bash int=1 while (( $int <= 5)) #for ((;;)) 循环也可以这么写 do echo $int let "int++" done rivsidn@rivsidn:~/demo/bash/test$ ./demo.sh 1 2 3 4 5