for循环
1、求1加到100的数字的合是多少
sum=0
for i in `seq 1 100`;do sum=$[sum+$i];echo "$sum";done
2、循环目录列表 [root@centos7 shell]# vi for.sh
#!/bin/bash
dir=/usr/local/sbin/
for a in ls $dir
do
if [ -d $a ]
then
echo $a
ls $a
fi
done
echo "No directory file!"
while循环
格式: while 条件;do…;done
1、当系统负载大于10的时候,发送邮件,每隔30秒执行一次。
while : 表示真命题,相当于while true
#!/bin/bash
while :
do
load=w|head -1 |awk -F 'load average:' '{print $2}' |cut -d . -f1
if [ $load -gt 10 ]
then
top |mail -s "load is high: $load" abc@111.com
fi
sleep 30
done
2、
#!/bin/bash
while :
do
read -p 'please input a num:' n
if [ -z "$n" ];then
echo "please input num"
continue
fi
echo $n
n1=echo $n|sed 's#[0-9]##g'
if [ -n "$n1" ];then
echo "please input num"
exit 2
else
echo $n
break
fi
done
#continue:中断本次while循环后重新开始; #break:表示跳出本层循环,即该while循环结束
break跳出循环
1、当等于3就跳出循环
#!/bin/bash
for i in seq 1 5
do
echo "$i"
if [ $i -eq 3 ]
then
break
fi
echo "$i"
done
echo "Finished!"
结果: [root@centos7 shell]# sh break.sh 1 1 2 2 3 Finished!
continue结束本次循环
1、当等于3了就跳过继续执行,本次循环结束,开始下一个循环
#!/bin/bash
for i in seq 1 5
do
echo "$i"
if [ $i -eq 3 ]
then
continue
fi
echo "$i"
done
echo "Finished!"
结果: 1 1 2 2 3 4 4 5 5 Finished!
exit退出整个脚本
1、当等于3就退出整个脚本
#!/bin/bash
for i in seq 1 5
do
echo "$i"
if [ $i -eq 3 ]
then
exit
fi
echo "$i"
done
select 选择器
1、 #!/bin/bash
echo "please input 1.w 2.top 3.free 4.quit" select com in w top free quit do case $com in w) w ;; top) top ;; free) free ;; *) exit ;; esac done
执行结果: [root@centos7 shell]# sh select.sh please input 1.w 2.top 3.free 4.quit
- w
- top
- free
- quit