Shell编程-case语句
时间:2020-02-23 14:45:07 来源:igfitidea点击:
在本教程中,我们将学习Shell编程中的Case条件语句。
与if语句类似,我们使用case语句来进行决策并根据某些匹配执行代码块。
case语法
case word in pattern1) # block of code for pattern1 ;; pattern2) # block of code for pattern2 ;; *) # default block ;; esac
其中," word"是与" pattern1"," pattern2"等匹配的某个值。
如果单词与任何模式匹配,则执行属于该模式的代码块。
';;'标记了代码块的结尾,使我们脱离了case。
*是默认模式。
如果找不到匹配项,则执行默认模式中的代码。
默认模式" *)"是可选的,可以省略。
esac(大小写相反)标志着case语句的结尾。
例1:编写一个Shell脚本从用户那里获取整数值并根据匹配结果打印一些消息
在下面的示例中,我们将打印数字。
#!/bin/sh # take a number from user echo "Enter number:" read num case $num in 1) echo "It's one!" ;; 2) echo "It's two!" ;; 3) echo "It's three!" ;; *) echo "It's something else!" ;; esac echo "End of script."
$sh num.sh Enter number: 10 It's something else! End of script. $sh num.sh Enter number: 2 It's two! End of script.
示例2:编写Shell脚本以显示问候语
在下面的示例中,我们将以用户名和一天中的时间作为输入并显示一些问候消息。
#!/bin/sh # take user name echo "Enter your name:" read name # take time of the day echo "Enter time of the day [Morning/Afternoon/Evening/Night]:" read daytime case $daytime in "Morning") echo "Good Morning $name" ;; "Afternoon") echo "Good Afternoon $name" ;; "Evening") echo "Good Evening $name" ;; "Night") echo "Good Night $name" ;; esac echo "End of script."
$sh greetings.sh Enter your name: theitroad Enter time of the day [Morning/Afternoon/Evening/Night]: Morning Good Morning theitroad End of script. $sh greetings.sh Enter your name: theitroad Enter time of the day [Morning/Afternoon/Evening/Night]: End of script.
在第二次运行中,我们没有收到任何问候消息,因为没有提供当天的时间,并且case语句中没有默认模式" *)"来处理这种情况。
因此,我们可以通过包含" *)"默认模式来修改上述代码以处理这种情况。
#!/bin/sh # take user name echo "Enter your name:" read name # take time of the day echo "Enter time of the day [Morning/Afternoon/Evening/Night]:" read daytime case $daytime in "Morning") echo "Good Morning $name" ;; "Afternoon") echo "Good Afternoon $name" ;; "Evening") echo "Good Evening $name" ;; "Night") echo "Good Night $name" ;; *) echo "Time of the day missing!" ;; esac echo "End of script."
$sh greetings-1.sh Enter your name: theitroad Enter time of the day [Morning/Afternoon/Evening/Night]: Time of the day missing! End of script.