首页 > 技术文章 > 5、shell分支

quyong 2017-04-10 11:04 原文

同其他高级语言程序一样,复杂的shell程序中经常使用到分支和循环控制结构,
bash,pdksh和tcsh分别都有两种不同形式的条件语句:if语句和case语句.
(1)if语句
语法格式:
bash/pdksh用法:
if [expression1]
then
commands1
elif [expression2]
commands2
else
commands3
if
tcsh用法:
if (expression1) then
commands1
else if (expression2) then
commands2
else
commands3
endif
含义:当expression1的条件为True时,shell执行then后面的commands1命令;当
expression1的条件为false并且expression2的条件满足为True时,shell执行
commands2命令;当expression1和expressin2的条件值同为false时,shell执行
commands3命令.if语句以他的反写fi结尾.
(2)case语句
case语句要求shell将一个字符串S与一组字符串模式P1,P2,...,Pn比较,当S与
某个模式Pi想匹配时,就执行相应的那一部分程序/命令.shell的case语句中字符
模式里可以包含象*这样的通配符.
语法格式:
bash/pdksh用法:
case string1 in
str1)
commands1;;
str2)
commands2;;
*)
commands3;;
esac
tcsh用法:
switch (string1)
case str1:
statements1
breaksw
case str2:
statements2
breaksw
default:
statements3
breaksw
endsw
含义:shell将字符串string1分别和字符串模式str1和str2比较.如果string1与str1匹配,则
shell执行commands1的命令/语句;如果string11和str2匹配,则shell执行commands2的命令/
语句.否则shell将执行commands3的那段程序/命令.其中,每个分支的程序/命令都要以两个
分号(;结束.

推荐阅读