continue 结束本次循环
eg:
[root@dl-001 sbin]# vim continue.sh
#!/bin/bash
for i in `seq 1 5`
do
echo "$i"
if [ $i -eq 3 ]
then
continue
fi
echo "$i"
done
echo "qqq"
[root@dl-001 sbin]# sh continue.sh
1
1
2
2
3
4
4
5
5
qqq
即,结束本次循环之后重新开始下一次循环。
exit退出整个脚本
eg:
[root@dl-001 sbin]# vim exit.sh
#!/bin/bash
for i in `seq 1 5`
do
echo "$i"
if [ $i -eq 3 ]
then
exit
fi
echo "$i"
done
[root@dl-001 sbin]# sh exit.sh
1
1
2
2
3
说明:退出整个脚本,后面的命令不会执行。
select循环
select也是循环的一种,它比较适合用在用户选择的情况下。
需求:运行脚本后,让用户去选择数字,选择1,会运行w命令,选择2运行top命令,选择3运行free命令,选择4退出。
#!/bin/bash
echo "Please chose a number, 1: run w, 2: run top, 3: run free, 4: quit"
echo
select command in w top free quit
do
case $command in
w)
w
;;
top)
top
;;
free)
free
;;
quit)
exit
;;
*)
echo "Please input a number:(1-4)."
;;
esac
done
执行结果如下:
sh select.sh
Please chose a number, 1: run w, 2: run top, 3: run free, 4: quit
1) w
2) top
3) free
4) quit
#? 1
16:06:58 up 109 days, 22:01, 1 user, load average: 0.11, 0.05, 0.01
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
root pts/0 222.128.156.84 16:05 0.00s 0.00s 0.00s w
#? 3
total used free shared buffers cached
Mem: 1020328 943736 76592 0 86840 263624
-/+ buffers/cache: 593272 427056
Swap: 2097144 44196 2052948
#?
我们发现,select会默认把序号对应的命令列出来,每次输入一个数字,则会执行相应的命令,命令执行完后并不会退出脚本。它还会继续让我们再次输如序号。序号前面的提示符,我们也是可以修改的,利用变量PS3即可,再次修改脚本如下:
#!/bin/bash
PS3="Please select a number: "
echo "Please chose a number, 1: run w, 2: run top, 3: run free, 4: quit"
echo
select command in w top free quit
do
case $command in
w)
w
;;
top)
top
;;
free)
free
;;
quit)
exit
;;
*)
echo "Please input a number:(1-4)."
esac
done
如果想要脚本每次输入一个序号后就自动退出,则需要再次更改脚本如下:
#!/bin/bash
PS3="Please select a number: "
echo "Please chose a number, 1: run w, 2: run top, 3: run free, 4: quit"
echo
select command in w top free quit
do
case $command in
w)
w;exit
;;
top)
top;exit
;;
free)
free;exit
;;
quit)
exit
;;
*)
echo "Please input a number:(1-4).";exit
esac
done