Control Structures
shell中有一系列的控制结构语句,这些语句同其他编程语言(如:C、C++等)都十分相似。接下来,将一一介绍这些控制结构语句。
if
结构:if condition then statments else statments fi
#!/bin/sh echo "Is it morning? Please answer yes or no" read timeofday if [ $timeofday = "yes" ]; then echo "Good morning" else echo "Good afternoon" fi exit 0
elif
同其他编程语言一样,elif的作用就是增加if语句更多的判断标准。
示例:#!/bin/sh echo "Is it morning? Please answer yes or no" read timeofday if [ $timeofday = "yes" ]; then echo "Good morning" elif [ $timeofday = "no" ]; then echo "Good afternoon" else echo "Sorry, $timeofday not recognized. Enter yes or no, please." exit 1 fi exit 0
注:在上面的程序中存在缺陷,运行该脚本,之后不输入任何东西直接回车,我们将得到一个错误信息。为什么会这样呢?问题就出在第一个if条件的变量timeofday在测试的时候,被认为是一个空白的字符串,即:
if [ = "yes" ]
因此,为了避免这种错误,我们需要用引号把变量给括起来。即:
if [ "$timeofday" = "yes"]
这样,在相同的情况下,该语句的表现形式是这样的:
if [ " " = "yes" ]
即我们给一个空变量做了一个测试,而这个测试在shell中是有效的。
for
使用for语句主要用来在一个给出的范围内循环测试条件是否成立,从而给出相应的结果。
结构:for variable in values do statements done
#!/bin/sh for foo in bar fud 43 do echo $foo done exit 0
注:如果我们将for foo in bar fud 43写成for foo in "bar fud 43"的话,引号内的字符串将被当成是一个字符串。
同时,我们也可以在for语句中使用通配符扩展来帮助我们得到一些简化的操作,示例如下:
#!/bin/sh for file in $(ls f*.sh) do lpr $file done exit 0
while
我们使用for语句是在一系列字符串中循环,但如果我们不清楚我们所要循环的个数时,这时我们就需要通过while来达到我们的要求。
结构:while condition do statements done
#!/bin/sh echo "Enter password:" read trythis while [ "$trythis" != "secret" ]; do echo "Sorry, try again" read trythis done exit 0
until
该语句同其他编程语言一样,相当于while的一个相反的条件检测。
结构:until condition do statements done
#!/bin/bash until who | grep "$1" > /dev/null do sleep 60 done #now rng the bell and announce the expected user. echo -e '\a' echo "****** $1 has just logged in ******" exit 0
注:通常情况下,如果一个循环至少需要运行一次,使用while循环;否则,使用until循环。
case
结构:case variable in pattern [ | pattern ] ...) statements;; pattern [ | pattern ] ...) statements;; ... esac
#!/bin/sh echo "Is it morning? Please answer yes or no" read timeofday case "$timeofday" in yes) echo "Good Morning";; no ) echo "Good afternoon";; y ) echo "Good Morning";; n ) echo "Good afternoon";; * ) echo "Sorry, answer not recognized";; esac exit 0
我们也可以通过使用通配符来简化该程序操作,同时获得更多有效且智能化的操作。示例如下:
#!/bin/sh ehco "Is it morning? Please answer yes or no" read timeofday case "$timeofday" in yes | y | Yes | YES ) echo "Good Morning";; n* | N* ) echo "Good Afternoon";; * ) echo "Sorry, answer not recognized";; esac exit 0
Lists
List分为两类:And 和 OR,即:“&&”和“||”。
AND
结构:statement1 && statement2 && statement3 && ...
AND list可以让我们执行一系列的命令,只有当前面的命令执行成功才可以执行后面的命令。
示例:#!/bin/sh touch file_one rm -f file_two if [ -f file_one ] && echo "hello" && [ -f file_two ] && echo "there" then echo "in if" else echo "in else" fi exit 0
OR
结构:statement1 || statement2 || statement3 || ...
OR list可以让我们执行一系列命令直到有一条命令成功为止。
示例:#!/bin/sh rm -f file_one if [ -f file_one] || echo "hello" || echo "there" then echo "in if" else echo "in else" fi exit 0
如果我们想要使用更多更复杂的程序块在AND和OR list中,我们可以使用{ }来完成。