shell脚本之case用法
你会经常发现自己在尝试计算一个变量的值,在一组可能的值中寻找特定值。在这种情形下,
你不得不写出很长的if-then-else语句,就像下面这样。
$ cat test25.sh #!/bin/bash # looking for a possible value # if [ $USER = "rich" ] then echo "Welcome $USER" echo "Please enjoy your visit" elif [ $USER = "barbara" ] then echo "Welcome $USER" echo "Please enjoy your visit" elif [ $USER = "testing" ] then echo "Special testing account" elif [ $USER = "jessica" ] then echo "Do not forget to logout when you're done" else echo "Sorry, you are not allowed here" fi $ $ ./test25.sh Welcome rich Please enjoy your visit
如上面的案例,我们需要做多个if判断来一一核对,代码量比较多,还容易乱,这时可以用case用法来减少代码量,
有了case命令,就不需要再写出所有的elif语句来不停地检查同一个变量的值了。case命
令会采用列表格式来检查单个变量的多个值。
#!/bin/bash # using the case command # case $USER in rich | barbara) echo "Welcome, $USER" echo "Please enjoy your visit";; testing) echo "Special testing account";; jessica) echo "Do not forget to log off when you're done";; *) echo "Sorry, you are not allowed here";; esac
case 用法也常用于启动脚本中
#!/bin/sh # Comments to support chkconfig on RedHat Linux # chkconfig: 2345 80 50 # description: A very fast and reliable Tomcat. export JAVA_HOME=/data/jdk8/ tomcat[1]="/data/Tomcat/" project="/data/www/kstore/" module="site boss mobile third open" webinf="/htdocs/WEB-INF/" war="/htdocs/war/" start(){ cache for i in ${tomcat[@]} do ${i}/bin/startup.sh sleep 60 done sleep 60 test } stop(){ for i in ${tomcat[@]} do ${i}/bin/shutdown.sh rm -rf ${i}/work/Catalina/ pid=$(ps -ef | grep ${i} | grep -v grep | awk '{print $2}') if [ "${pid}" != "" ];then kill -9 ${pid} fi sleep 5 done cache test } test(){ for i in ${tomcat[@]} do pid=$(ps -ef | grep ${i} | grep -v grep | awk '{print $2}') if [ "${pid}" != "" ];then echo "${i} is running!" else echo "${i} may not be running!" fi done } change(){ transfer(){ a=`find ~ -name "*.war" | wc -l` if [ ${a} -gt 0 ];then mv ${war}/*.war ${war}/backup/ mv ~/*.war ${war} fi for i in ${module[@]} do b=$(ls -A ${war} | grep "${i}") if [ "${b}" != "" ];then echo ${i} fi done } app=$(transfer) for i in ${app[@]} do rm -rf ${project}${i} mkdir ${project}${i} unzip -q ${war}/*${i}*.war -d ${project}${i} cp -rf ${webinf} ${project}${i} sed -i "/amq.destination/s/boss/${i}/g" ${project}/${i}/WEB-INF/classes/com/ningpai/web/config/amq.properties done } cache(){ sync echo 3 > /proc/sys/vm/drop_caches } case "$1" in #startup tomcat start) start ;; #stop tomcat stop) stop ;; #restart tomcat restart) stop start ;; #reload tomcat reload) stop change start ;; #test tomcat status) test ;; #load tomcat load) change start ;; *) echo "Use tomcat start|stop|status|restart|reload|load" ;; esac