until 循環
until conditon ;do
循環體
done
進入條件:false
退出條件:true
continue[N]:提前結束第N層的本輪循環,而直接進入下一輪判斷;
while conditon;do
cmd1
..
if conditon;then
continue
fi
cmd
...
break[N];提前結束循環;
cmd..
break
求質數
#!/bin/bash
#
for ((i=2;i<=$1;i++));do
for ((j=2;j<=i/2;j++));do
if ((i%j==0));then
# echo "$i 不是質數。。"
break
fi
done
if ((j>i/2));then
# echo ".................$i 是素數。。。。。。。。。。。。"
echo -n "$i,"
fi
執行個體:求100以内所有偶數之和
declare -i i=0
declare -i sum=0
while [ $i -le 100 ];do
let i++
if [ $[$i%2] -eq 1 ];then
let sum+=$i
echo "$sum"
建立死循環
while true;do
until false; do
每三秒檢查使用者是否登入
read -p "Enter a user name :" username
if who | grep "^$username" &>/dev/null;then
sleep 3
echo "$username logged on." >> /tmp/user.log
while !(until兩種方式都可以) who | grep "^$username" &>/dev/null;do
while循環的特殊用法:
while read line; do
done < /path/from/somefile #輸入重定向
注意:依次讀取檔案的每一行,且将行指派給變量line
找出id号為偶數的所有使用者,顯示其使用者名和ID号
查找id為偶數的使用者
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 `"
done < /etc/passwd
for循環的特殊格式:
for((控制變量初始化;條件判斷表達式;控制變量的修正表達式));do
求100以内所有正整數之和
for ((i=1;i<=100;i++));do
echo $sum
九九乘法表
#
for ((x=1;x<=9;x++));do
for((y=1;y<=$x;y++));
do
echo -e -n "$[x]X$[y]=$[$x*$y]\t"
echo
根據提示輸入指令。傳回相應的資訊。
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
if [ $cmd == cpu ];then
lscpu
elif [ $cmd == mem ];then
free
elif [ $cmd == disk ];then
fdisk -l
else
echo "Quit"
exit 0
條件判斷:case語句
case 變量引用 in
PAT1)
分之1
;;
PAT2)
分之2
PAT3)
分之3
*)
預設分之
esac
case "$cmd" in
cpu)
mem)
disk)
本文轉自阿倫艾弗森 51CTO部落格,原文連結:http://blog.51cto.com/perper/1954582,如需轉載請自行聯系原作者