shell循环
2013-06-12shell脚本经常需要用到循环。在提示符下直接键入help将看到下面所有shell循环命令的基本用法。键入man bash会获得更多更详细相关信息。
1、for循环
for ((i=1;i<11;i++))
#for i in {01..10}
do
#mkdir `printf data"%02d\n" $i`;
mkdir $(printf data"%03d\n" $i)
done
2、while循环
#!/bin/sh
i=1
#while [[ i -lt 11 ]];
#while [ $i -lt 11 ];
while [ $i < 11 ];
do
echo $i;
#((i=i+1));
let i=i+1
done
3、while infinite loops
#!/bin/sh
i=1;
while :;
do
echo $i;
((i=i+1));
if [[ i -gt 10 ]];then
break;
fi
done
4、until循环
#!/bin/sh
x=1
until [ $x -ge 11 ];
do
echo $x
let x=x+1;
#x=`expr $x + 1`
done
5、until example
#bin/bash
i=1
s=0
until [[ i -gt 30 ]];
do
((s=s+i));
((i=i+1));
done
echo "The result is $s"
6、Here is a sample shell code to calculate factorial using while loop阶乘:
#!/bin/bash
counter=$1
factorial=1
while [ $counter -gt 0 ]
do
factorial=$(( $factorial * $counter ))
counter=$(( $counter - 1 ))
done
echo $factorial
To run just type:
$ chmod +x script.sh
$ ./script.sh 5
Output: 120
7、select循环的典型例子
vi select.sh
#!/bin/sh
echo "What is your favourite OS?"
select var in "Linux" "Windows" "Unix" "Other";
do
break;
#select本身就是一个循环,break是当选择后,就跳出循环
done
echo "You have selected $var"
#sh select.sh
What is your favourite OS?
1) Linux
2) Windows
3) Unix
4) Other
#? 1
You have selected Linux
8, select+while
#!/bin/sh
while echo "display current netconfig:"
do
select cmd in "ifconfig -a" "route" "netstat2" "quit"
do
case $cmd in
"ifconfig -a")
/sbin/ifconfig -a;;
"route")
netstat -rn;;
"netstat2")
netstat -nat|grep :80|awk '{print awk $NF}'|sort|uniq -c|sort -n;;
"quit")
exit 0;;
*)
continue;;
esac
break
done
done
9、calculate
((i=i+1));
let i=i+1;
x=$(( $x + 1 ))
x=`expr $x + 1`