shell 控制语句练习
在介绍控制语句前,先说下test 和 []
test 和[]命令可以 对三类表达式进行测试
- 字符串比较
- 文件测试
- 数字比较
1.字符串比较 shell对大小写敏感,为字符串变量加上引号是一个好的编程习惯
选项 | 描述 |
---|---|
-z str | 当字符串str的长度为0时返回真 |
-n str | 当字符串str的长度大于0时返回真 |
str1 = str2 | 当字符串str1和str2相等时返回真 |
str1 != str2 | 当字符串str1和str2不相等时返回真 |
例子:
#! /bin/bash
#下面脚本判断用户输入的是否为空
read password
if [ -z "$password" ]
then
echo "请输入密码"
fi
2.文件测试 用于判断一个文件是否满足特定的条件
选项 | 描述 |
---|---|
-f file | 当file是常规文件(不包括符号链接、管道、目录等)的时候返回为真 |
-b file | 当file是块设备文件时返回真 |
-c file | 当file是字符文件时返回真 |
-h file | 当file是符号链接文件时返回真 |
-p file | 当file是管道时返回真 |
-s file | 当file存在且大小为0时返回真 |
-d pathname | 当pathname为一个目录时返回真 |
-e pathname | 当pathname指定文件或目录存在时返回真 |
-g pathname | 当pathname指定文件或目录设置了SGID位时返回真 |
-u pathname | 当pathname指定文件或目录设置了SUID位时返回真 |
-r pathname | 当pathname指定文件或目录设置了可读权限时返回真 |
-w pathname | 当pathname指定文件或目录设置了可写权限时返回真 |
-x pathname | 当pathname指定文件或目录设置了可执行权限时返回真 |
-o pathname | 当pathname指定文件或目录被当前进程的用户拥有时返回真 |
例子:
if [ -x /usr/tmp/测试脚本.sh ];then
echo "该文件具有执行权限"
fi
3.数字比较
- test 和 [] 命令在数字比较方面只能用来比较整数(正负都行)
- test用法: test int1 option int2 比较数字int1和数字int2 option表示比较选项
[]用法:[ int1 option int 2 ]
选项 | 对应的英语单词 | 描述 |
---|---|---|
-eq | equal | 如果相等返回为真 |
-ne | not equal | 如果不相等返回为真 |
-lt | lower then | int1小<int2返回为真 |
-le | lower or equal | int1<=int2 返回为真 |
-gt | greater then | int1>int2返回为真 |
-le | greather or equal | int1>=int2 返回为真 |
例子
if [ $status -eq 0];then
echo "程序正在运行"
else
echo "程序未处于正确的运行状态"
fi
复合表达式
test 和 [] 命令本身内建了操作符来完成条件表达式的组合
操作符 | 描述 |
---|---|
! | “非”运算 |
-a | “与”运算 |
-o | “或”运算 |
例子
if [ -f $@ -a -x /usr/bin/vi ];then
cp $@ $@.bak
vi $@
fi
解释: $@ 执行脚本是传入的参数列表 例./start.sh param1 param2 param3
$@ 即为[param1,param2,param3]
这个脚本接收用户的输入,如果用户提供的文件存在,并vi编辑器存在,就先复制这个文件,然后调用vi编辑器打开
-a 之前的判断条件如果不满足就会跳出if(逻辑与的操作),不会执行 -a 之后的判断条件
if [ ! -z $password -o /usr/local/public_key ];then
echo "密码不为空,或者存在密码文件"
fi
注意:shell的条件操作符&&和 || 可以用来题材test和[]命令内建的-a和-o。区别就是&&和 || 连接的是两条test 或[]命令,而-a和-o连接的是在同一条test 或 [] 命令中。具体使用哪种方式没有好坏之分,习惯而已
以下是if elif else 例子
#! /bin/bash
echo "请输入年龄"
read age
if[ $age -gt 0 ] && [ $age -le 12 ];then
echo "hi,小朋友"
if[ $age -gt 12 -a $age -le 30 ];then
echo "hi,小伙子"
if[ "$age" -gt "30" ] && [ $age -le 60 ];then
echo "hi,哥们"
if(("$age" > "60")) && (($age <= 80));then
echo "hi,老伙计"
if(($age > 80 && $age <= 120));then
echo "hi,老人家"
else
echo "请输入正确的年龄"
if
以下是case 多选结构例子
#! /bin/bash
echo "请输入身份"
read identify
case $identify in
student)
echo "你的身份是学生"
;;
teacher)
echo "你的身份是教师"
;;
*)
echo "请输入正确的身份信息"
;;
esac
还没有评论,来说两句吧...