case语句格式
case
语句如果某个选项没有任何语句,也要加;; 否则会出下边错误
test: line 166: syntax error near unexpected token `)'
test: line 166: `"system hostname config")'
为什么输入no,仍不匹配到[no]
原来[]是专门针对单字符的值,如果用[no],就是n和o之一
改正
一个getyn()函数的例子
if, case,匹配字符串最常见,但如何匹配一段很长的输出,一堆文字?最好方法,用“*”,如:*"command
not found"*
例2.匹配file命令输出的一堆文字,以获知文件类型
用’ ’ 取输出,然后用CASE+*对输出做修饰处理.
最典型的shell
case命令匹配命令行,用于sys v启动脚本的start|stop|restart|status处理
case "$@" in
($@ 字符串数组:以"参数1" "参数2" ... 的字符串数组形式保存所有参数
对于单个参数的情况,$@就是一个字符串)
start)
echo -n "Starting firewall..."
。。。
echo "OK!"
exit 0
;;
stop)
echo -n "Stopping firewall..."
。。。
exit 0
;;
restart)
$0 stop $0即执行原始程序
$0 start
;;
status)
clear
echo ">------------------------------------------"
iptables -L
echo ">------------------------------------------"
iptables -t nat -L POSTROUTING
exit 0
*)
echo "Usage: $0 {start|stop|restart|status}"
exit 1
esac
|
# vi test.sh : echo "input : " read num echo "the input data is $num" case $num in 1) echo "January";; 2) echo "Feburary";; 5) echo "may" *) echo "not correct input";; esac |
|
# sh ./test.sh input : 2 the input data is 2 Feburary # sh ./test.sh input : ter the input data is ter not correct input |
test: line 166: syntax error near unexpected token `)'
test: line 166: `"system hostname config")'
原来[]是专门针对单字符的值,如果用[no],就是n和o之一
|
case $yn in |
|
[macg@mac-home ~]$ sh test.sh enter y/n : no only accept Y,y,N,n,YES,yes,NO,no |
|
case $yn in |
|
[macg@mac-home ~]$ sh test.sh enter y/n : no |
|
getyn( ) { while echo "enter y/n :" do done } |
|
if getyn then echo " your answer is yes" else echo "your anser is no" fi |
|
[macg@machome ~]$ vi test.sh var=$(ls -l $1) echo "output is $var" case $var in "-rw-rw-r--"*) echo "this is not a execute file";; "-rwxrwxr-x"*) echo "this is a execute file"; 注意*在双引号外边 esac |
|
[macg@machome ~]$ sh test.sh 22.txt output is -rw-rw-r-- this is not a execute file [macg@machome ~]$ chmod +x 22.txt [macg@machome ~]$ sh test.sh 22.txt output is -rwxrwxr-x this is a execute file |
用’ ’ 取输出,然后用CASE+*对输出做修饰处理.
|
[macg@machome ~]$ vi test.sh var=`file $1` echo "output is $var" case $var in "$1: ASCII text"*) echo "this is a text file";; "$1: directory"*) echo "this is a directory";; 注意*在双引号外边 esac |
|
[macg@machome ~]$ sh test.sh 22.txt output is 22.txt: ASCII text this is a text file [macg@machome ~]$ sh test.sh test-dir output is test-dir: directory this is a directory |
($@ 字符串数组:以"参数1" "参数2" ... 的字符串数组形式保存所有参数
对于单个参数的情况,$@就是一个字符串)
restart)
status)
Shell脚本中case语句的应用与案例解析
本文深入探讨了Shell脚本中的case语句的使用方法及实例,包括基本语法、输入验证、匹配特定字符、处理复杂输出、系统命令匹配、文件类型识别、系统服务控制以及自定义函数应用等。通过详细解析每个案例,读者能够掌握case语句在不同场景下的灵活运用。
1358

被折叠的 条评论
为什么被折叠?



