until-continue-break-for-case
until 循環
until conditon ;do
循環體
done
進入條件:false
退出條件:true
continue[N]:提前結束第N層的本輪循環,而直接進入下一輪判斷;
while conditon;do
cmd1
..
if conditon;then
continue
fi
cmd
...
done
break[N];提前結束循環;
while conditon;do
cmd..
if conditon;then
break
fi
cmd
..
done
實例:求100以內所有偶數之和
#!/bin/bash
#
declare -i i=0
declare -i sum=0
while [ $i -le 100 ];do
let i++
if [ $[$i%2] -eq 1 ];then
continue
fi
let sum+=$i
done
echo "$sum"
創建死循環
while true;do
循環體
done
until false; do
循環體
done
每三秒檢查用戶是否登錄
#!/bin/bash
#
read -p "Enter a user name :" username
while true;do
if who | grep "^$username" &>/dev/null;then
break
fi
sleep 3
done
echo "$username logged on." >> /tmp/user.log
#!/bin/bash
#
read -p "Enter a user name :" username
while !(until兩種方式都可以) who | grep "^$username" &>/dev/null;do
sleep 3
done
echo "$username logged on." >> /tmp/user.log
while循環的特殊用法:
while read line; do
循環體
done < /path/from/somefile #輸入重定向
註意:依次讀取文件的每一行,且將行賦值給變量line
找出id號為偶數的所有用戶,顯示其用戶名和ID號
查找id為偶數的用戶
#!/bin/bash
#
while read line ;do
if [ $[ `echo $line | cut -d: -f3` % 2 ] -eq 0 ];then
echo -e -n "username:`echo $line | cut -d: -f1`\t"
echo "uid:`echo $line | cut -d: -f3 `"
fi
done < /etc/passwd
for循環的特殊格式:
for((控制變量初始化;條件判斷表達式;控制變量的修正表達式));do
循環體
done
求100以內所有正整數之和
#!/bin/bash
#
declare -i sum=0
for ((i=1;i<=100;i++));do
let sum+=$i
done
echo $sum
九九乘法表
#!/bin/bash
#
for ((x=1;x<=9;x++));do
for((y=1;y<=$x;y++));
do
echo -e -n "$[x]X$[y]=$[$x*$y]\t"
done
echo
done
根據提示輸入命令。返回相應的信息。
#!/bin/bash
#
while true;do
cat << EOF
cpu)show cpu information
mem)show memory information
disk)show disk information
quit)quit;
=============================
EOF
read -p "Enter a option:" cmd
while [ "$cmd" != ‘cpu‘ -a "$cmd" != ‘mem‘ -a "$cmd" != ‘disk‘ -a "$cmd" != ‘quit‘ ] ;do
read -p "error cmd ...請重新輸入:" cmd
done
if [ $cmd == cpu ];then
lscpu
elif [ $cmd == mem ];then
free
elif [ $cmd == disk ];then
fdisk -l
else
echo "Quit"
exit 0
fi
done
條件判斷:case語句
case 變量引用 in
PAT1)
分之1
;;
PAT2)
分之2
;;
PAT3)
分之3
;;
...
*)
默認分之
;;
esac
#!/bin/bash
#
while true;do
cat << EOF
cpu)show cpu information
mem)show memory information
disk)show disk information
quit)quit;
=============================
EOF
read -p "Enter a option:" cmd
while [ "$cmd" != ‘cpu‘ -a "$cmd" != ‘mem‘ -a "$cmd" != ‘disk‘ -a "$cmd" != ‘quit‘ ] ;do
read -p "error cmd ...請重新輸入:" cmd
done
case "$cmd" in
cpu)
lscpu
;;
mem)
free
;;
disk)
fdisk -l
;;
*)
echo "Quit"
exit 0
;;
esac
done
until-continue-break-for-case