#!/bin/bash while test 2 -gt 1 do echo yes sleep 1 # 休眠1秒 done
结果:
1 2 3 4
yes yes yes ...
while2.sh 代码
1 2 3 4 5 6
#!/bin/bash while [ 2 -gt 1 ] do echo yes sleep 1 done
结果:
1 2 3 4
yes yes yes ...
while3.sh
1 2 3 4 5 6
#!/bin/bash while [ "123" != "321"] do echo yes sleep 1 done
结果:
1 2 3 4
yes yes yes ...
4.3.3 判断
4.3.3.1 单分支
1 2 3 4
if 测试条件 then 选择分支 fi
if1.sh 代码
1 2 3 4 5 6
#!/bin/bash flag=$1 if [ $flag -eq 1 ] then echo one fi
结果
1 2 3 4
[root@samba shell]# sh if1.sh 1 one [root@samba shell]# sh if1.sh 2 [root@samba shell]# sh if1.sh 3
if2.sh 代码
1 2 3 4 5 6 7 8 9 10 11
#!/bin/bash if [ $# -lt 1 ] then echo "not found param" exit 100 # 返回状态码 100 fi flag=$1 if [ $flag -eq 1 ] then echo one fi
结果
1 2 3 4 5 6 7 8
[root@samba shell]# sh if2.sh not found param [root@samba shell]# echo $? # 查看状态码 100 [root@samba shell]# sh if2.sh 1 one [root@samba shell]# echo $? # 查看状态码 0
4.3.3.2 多分支
1 2 3 4 5 6
if 测试条件 then 选择分支1 else 选择分支2 fi
if3.sh
1 2 3 4 5 6 7 8 9 10 11 12 13
#!/bin/bash if [ $# -lt 1 ] then echo "not found param" exit 100 fi flag=$1 if [ $flag -eq 1 ] then echo one else echo "not support" fi
结果
1 2 3 4 5 6
[root@samba shell]# sh if3.sh 1 one [root@samba shell]# sh if3.sh 2 not support [root@samba shell]# sh if3.sh not found param
if4.sh
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#!/bin/bash if [ $# -lt 1 ] then echo "not found param" exit 100 fi flag=$1 if [ $flag -eq 1 ] then echo one elif [ $flag -eq 2 ] then echo two else echo "not support" fi
结果
1 2 3 4 5 6 7 8
[root@samba shell]# sh if4.sh 1 one [root@samba shell]# sh if4.sh 2 two [root@samba shell]# sh if4.sh 3 not support [root@samba shell]# sh if3.sh not found param