select也是循环的一种,它比较适合用在用户选择的情况下。

比如,我们有一个这样的需求,运行脚本后,让用户去选择数字,然后执行命令!

#!/bin/bash
select mysql_v in 5.1 5.6
do
case $mysql_v in
5.1)
echo "you choose the 5.1"
#break                                        /break这行被注释掉了 
;;
5.6)
echo "you choose the 5.6"
#break                                       /break这行被注释掉 
;;
esac
done

然后执行此脚本

[root@xinlianxi sbin]# sh 3.sh
1) 5.1
2) 5.6
#? 1
you choose the 5.1
#? 2
you choose the 5.6
#? 1
you choose the 5.1
#? 1
you choose the 5.1
#? 2
you choose the 5.6
#? 2
you choose the 5.6
#?              /会发现,只要不停的选择就会继续执行下去,而不会退出!

在脚本中加入break行:

#!/bin/bash
select mysql_v in 5.1 5.6
do
case $mysql_v in
5.1)
echo "you choose the 5.1"
break                              /break未被注释 
;;
5.6)
echo "you choose the 5.6"
break                              /break未被注释 
;;
esac
done

再次执行此脚本:会发现每次选择完,执行之后就会退出,select实际上也是一个循环,break的作用就是退出循环!

[root@xinlianxi sbin]# sh 3.sh
1) 5.1
2) 5.6
#? 1
you choose the 5.1
[root@xinlianxi sbin]# sh 3.sh
1) 5.1
2) 5.6
#? 2                                      /选择是前面的那个“#?”符号是可以修改的,可以用ps3修改,如下脚本 
you choose the 5.6
[root@xinlianxi sbin]# vim 3.sh
#!/bin/bash
PS3="Please select a number: "                         /在脚本中加入此行,再次运行! 
select mysql_v in 5.1 5.6
do
case $mysql_v in
5.1)
echo "you choose the 5.1"
break
;;
5.6)
echo "you choose the 5.6"
break
;;
esac
done
运行结果:
[root@xinlianxi sbin]# sh 3.sh
1) 5.1
2) 5.6
Please select a number: 1
you choose the 5.1