shell 学习之case语句

简介:

一般建议变量用引号括起来

-v 显示信息 

case 
shift
把刚才的变量踢掉

 

一、case语句:语法结构
case stitch in
value1)
    statement
    ...
    ;;
value2)
    statement
    ...
    ;;
*)
;;

esac

 

示例(给出选项让用户选择,然后根据用户所选显示出相应的信息):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
[root@lovelace  case ] # cat showmenu.sh
#!/bin/bash
#Version:0.1
#Auther:lovelace
#pragram:show menu and wait user choice
#
#difine an function to display the menu
showmenu(){
echo  -n  '+----------'
echo   -n -e  "\033[1;32mshowmenu\033[0m"
echo  '-----------+'
echo  -e  "| \033[31md|D) show disk information\033[0m  |"
echo  -e  "| \033[31mm|M) show memory usage\033[0m      |"
echo  -e  "| \033[31ms|S) show swap usage\033[0m        |"
echo  -e  "| \033[31mq|Q) quitting\033[0m               |"
echo  -n  '+-------------'
echo   -n -e  "\033[5,33mEND\033[0m"
echo  '--------------+'
}
#call showmenu function
echo
showmenu
echo
#read the argument for user input
read  -p  "Your choice is:"  choice
#use while statement to loop
while  "$choice"  !=  "q"  -o  "$choice"  !=  "Q"  ]; do
#jugement the choice values and dispaly the result
case  $choice  in
d|D)
echo  "Disk information:"
df  -h
;;
m|M)
echo  "Memory information:"
free  -m |  grep  "Mem"
;;
s|S)
echo  "Swap information:"
free  -m |  grep  "Swap"
;;
q|Q)
echo  "quitting...."
exit  8
;;
*)
echo  "Unknow argument."
;;
esac
#call showmenu function again
echo
showmenu
#read user input again
echo
read  -p  "Please select again:"  choice
done

 

131747938.jpg

131751899.jpg

 

后记:这个好像就只是提了下case的语法结构,case在进行条件判断的时候相对于if来讲,个人更直观一些,不管怎么讲,脚本注重的是实现的目的,而不是过程,所以不管黑猫白猫,只要能抓住老鼠,就是好猫。



本文转自lovelace521 51CTO博客,原文链接:http://blog.51cto.com/lovelace/1211898,如需转载请自行联系原作者

相关文章
|
6天前
|
Linux Shell 文件存储
【Linux技术专题】「夯实基本功系列」带你一同学习和实践操作Linux服务器必学的Shell指令(深入df和dh的区别和探索)
【Linux技术专题】「夯实基本功系列」带你一同学习和实践操作Linux服务器必学的Shell指令(深入df和dh的区别和探索)
52 1
|
6天前
|
运维 Shell Python
Shell和Python学习教程总结
Shell和Python学习教程总结
|
6天前
|
Shell
shell学习(六) 【case多条件分支语句】
shell学习(六) 【case多条件分支语句】
19 1
|
6天前
|
Shell 应用服务中间件 nginx
shell学习(七) 【shell 函数】
shell学习(七) 【shell 函数】
13 1
|
6天前
|
Shell Perl
shell学习(九) 【shell sed用法】
shell学习(九) 【shell sed用法】
13 0
|
6天前
|
机器学习/深度学习 Shell Windows
shell学习(八) 【shell 正则 匹配符和限定符】
shell学习(八) 【shell 正则 匹配符和限定符】
10 1
|
6天前
|
Shell 应用服务中间件 开发工具
shell 学习(二) shell语法【特殊字符、转义字符、shell 字体颜色和字体背景】
shell 学习(二) shell语法【特殊字符、转义字符、shell 字体颜色和字体背景】
13 0
|
6天前
|
Shell
shell 学习(四)【if语法 for循环控制】
shell 学习(四)【if语法 for循环控制】
17 0
|
6天前
|
Shell
Shell脚本中的`case`语句
Shell脚本中的`case`语句
36 5
|
6天前
|
监控 Shell Linux
Linux如何系统的学习shell方法
Linux如何系统的学习shell方法
38 0