linux shell脚本基础-----2
来源:互联网 发布:淘宝购买力人群统计 编辑:程序博客网 时间:2024/05/22 06:11
2.2 条件及控制结构
条件: test 或 [命令。 当使用[命令时,还需要使用]来结尾。
test命令的退出码(表明条件是否被满足)决定是否需要执行后面的条件代码。
例如:
if test -f fred.cthen echo "test success"fiif [ -f fred.c ]then echo "test success"fiif [ -f fred.c ]; then echo "test success"fi
注意:
1. [和被检查的条件之间必须留出空格 ;
2. then可和if放在一行,但必须在前面加分号
条件类型: test命令可以使用的条件类型可以归为3类:字符串比较、算术比较和与文件有关的条件测试
控制结构:
1. if 语句
if conditionthen statementselse #或elif statementsfi
#!/bin/shecho "Is it morning? Please answer yes or no"read timeofdayif [ "$timeofday" = "yes" ] #注意,如果用if [ $timeofday = "yes" ],可能变成 if [ = "yes" ]then echo "Good morning"elif [ "$timeofday" = "no" ] ; then echo "Good afternoon"else echo "Sorry, $timeofday not recognized. Enter yes or no" exit 1fi exit 0
2. for 语句
#/bin/sh# 固定字符串实例for foo in bar fud 43do echo $foodone# 使用通配符扩展的for循环for file in $(ls f*.sh); do echo $filedoneexit 0
3. while和until语句
# 若condition为真,则执行statements,不满足条件就会终止while condition do statemensts done# 若condition不为真,则执行statements,即条件不满足时执行statementsuntil condition do statementsdone
4. case语句
case variable in pattern [ | pattern] ... ) statements;; pattern [ | pattern] ... ) statements;; ... esac
注意:
每个模式行都已双分号(;;)结尾;
要特别小心,case将使用第一个匹配的模式,即使后续的模式有更加精确的匹配也是如此。
#/bin/shecho "Is it morning? Please answer yes or no"read timeofdaycase "$timeofday" in yes) echo "Good Morning";; no ) echo "Good afternoon";; y ) echo "Good Morning";; n ) echo "Good afternoon";; * ) echo "Sorry, answer not recognized";; esaccase "$timeofday" in yes | y | Yes | YES) echo "Good Morning";; n* | N* ) echo "Good afternoon";; * ) echo "Sorry, answer not recognized";; esacexit 0
4. 命令列表
statement1 && statement2 && statement3 && ... #从左到右顺序执行每条命令,直到有条命令返回false或列表中所有命令执行完毕。&&的作用是检查前一条命令的返回值。statement1 || statement2 || statement3 || ... #从左到右顺序执行每条命令,直到有条命令返回true或列表中所有命令执行完毕。
5. 语句块
如果想在某些只允许使用单个语句的地方(比如&&或||列表中)使用多条语句,可以把它们括在{}内来构成一个语句块。
0 0
- linux shell脚本基础-----2
- Linux Shell脚本基础
- Linux Shell脚本基础
- Linux shell脚本基础
- Linux shell脚本基础
- Linux Shell 脚本基础
- 【Linux基础】shell脚本
- Linux Shell脚本编写基础(2)
- linux基础3.12shell脚本2
- linux shell脚本编写基础
- Linux shell脚本编写基础
- Linux shell脚本编写基础
- Linux shell脚本编写基础
- Linux shell脚本编写基础
- Linux shell脚本编写基础
- Linux shell脚本编写基础
- Linux shell 脚本编程基础
- Linux shell脚本基础学习
- jquery学习
- vim基本操作---2
- vim基本操作---3
- vim配置文件说明
- linux shell脚本基础-----1
- linux shell脚本基础-----2
- linux shell脚本基础-----3
- C语言之关键字
- android开发环境搭建
- android模拟器使用
- android手机拨号器实现
- kmp算法
- OpenCV基础篇之像素操作对比度调节
- android-为应用单元测试