一般建议变量用引号括起来
-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
|
后记:这个好像就只是提了下case的语法结构,case在进行条件判断的时候相对于if来讲,个人更直观一些,不管怎么讲,脚本注重的是实现的目的,而不是过程,所以不管黑猫白猫,只要能抓住老鼠,就是好猫。
本文转自lovelace521 51CTO博客,原文链接:http://blog.51cto.com/lovelace/1211898,如需转载请自行联系原作者