企业面试题12:打印选择菜单,一键安装Web服务:
[root@oldboyscripts]# sh menu.sh
1.[install lamp]
2.[install lnmp]
3.[exit]
pls input the num you want:
要求:
1、当用户输入1时,输出“startinstalling lamp.”然后执行/server/scripts/lamp.sh,脚本内容输出”lampis installed”后退出脚本;
2、当用户输入2时,输出“startinstalling lnmp.”然后执行/server/scripts/lnmp.sh输出”lnmpis installed”后退出脚本;
3、当输入3时,退出当前菜单及脚本;
4、当输入任何其它字符,给出提示“Input error”后退出脚本。
5、要对执行的脚本进行相关条件判断,例如:脚本是否存在,是否可执行等。
思路:利用函数来分块实现功能,实现菜单循环,可以调用函数实现,也就是可以不用循环语句来实现。
答案:
[root@nfs_server scripts]# cat menu.sh
#!/bin/bash
menu(){
cat<<EOF
####################
# 1.[INSTALL LAMP] #
# 2.[INSTALL LNMP] #
# 3.[EXIT] #
####################
EOF
read -t 20 -p "pls input the num you want:" a
}
read1(){
if [ "$a" == "1" ]
then
echo "start installing lamp...."
[ -f /server/scripts/lamp.sh ]&& /bin/sh /server/scripts/lamp.sh || echo "!!!!!! the lamp.sh scripts is not exist,pls create it!!!!!!!"
menu
read1
elif [ "$a" == "2" ]
then
echo "start installing lnmp...."
[ -f /server/scripts/lnmp.sh ]&& /bin/sh /server/scripts/lnmp.sh ||echo "!!!!!!the lnmp.sh scripts is not exist,pls create it!!!!!!"
menu
read1
elif [ "$a" == "3" ]
then
echo "exiting...."
exit
else
echo "input error ,pls input num!!!"
exit 3
fi
}
menu
read1
原文链接:20道必会shell题第12题,转载请注明来源!

思维严谨!