shell编程之条件语句——if与case

发布时间:2020-07-11 23:34:08 作者:wx5d8a17c45cb5b
来源:网络 阅读:182

shell编程之条件语句——if与case

一、文件测试

1.1test 命令

测试特定的表达式是否成立,成立返回值为0,反之,非0

test 条件表达式

[ 条件表达式 ] ——内容与括号之间加空格

文件测试

[ 操作符 文件或者目录 ]

常用的测试操作符
●-d:测试是否为目录(Directory)
●-e:测试目录或文件是否存在(Exist)
●-f:测试是否为文件(File)
●-r:测试当前用户是否有权限读取(Read)
●-w:测试当前用户是否有权限写入(Write)
●-x: 测试当前用户是否有权限执行(Excute)

实例如下(新手务必自己动手敲一敲体验理解):

[root@localhost ~]# ls -l shell/
总用量 16
-rw-r--r--. 1 root root 134 11月 25 19:59 demo.sh
-rwxr-xr-x. 1 root root 274 11月 25 18:58 state.sh
-rwxr-xr-x. 1 root root 208 11月 25 19:17 sujiaju.sh
-rwxr-xr-x. 1 root root 345 11月 25 19:11 welcome.sh

[root@localhost ~]#  [ -d shell/ ]          //第一种测试方法,对当前用户有效,或者test -d shell/
[root@localhost ~]# echo $?
0
[root@localhost ~]#  [ -d shell/state.sh ]
[root@localhost ~]# echo $?
1
[root@localhost ~]# test -d shell/           //第二种测试方法,对当前用户有效
[root@localhost ~]# echo $?
0
[root@localhost ~]# test -d shell/welcome.sh 
[root@localhost ~]# echo $?
1

[root@localhost ~]# test -x shell/welcome.sh 
[root@localhost ~]# echo $?
0
[root@localhost ~]# test -x shell/demo.sh 
[root@localhost ~]# echo $?
1

//上述过程可以使用&&一次执行
[root@localhost ~]# test -x shell/welcome.sh && echo "yes"
yes
[root@localhost ~]# echo $?
0
[root@localhost ~]#  [ -d shell/state.sh ]&& echo "yes"
[root@localhost ~]# echo $?
1

test 命令也可以用于判断文件之间的关系:

1.2整数值比较

[ 整数1 操作符 整数2]

■常用的测试操作符
●-eq:等于(Equal)
●-ne:不等于(Not Equal)
●-gt:大于(Greater Than)
●-lt: 小于(Lesser Than)
●-le: 小于或等于(Lesser or Equal)
●-ge:大于或等于(Greater or Equal)

参照实例:

[root@localhost shell]# [ 5 -gt 3 ]&&echo "yes"
yes
[root@localhost shell]# [ 5 -lt 3 ]&&echo "yes"
[root@localhost shell]# 

1.3字符串比较

●格式1
[ 字符串1 = 字符串2 ]
[ 字符串1 != 字符串2 ]
●格式2
[ -Z字符串]
■常用的测试操作符
●=:字符串内容相同
●!=:字符串内容不同,!号表示相反的意思
●-Z:字符串内容为空

[root@localhost shell]# [ hello = hello ]&&echo "yes"
yes
[root@localhost shell]# [ hello = hell ]&&echo "yes"
[root@localhost shell]# [ hello != hell ]&&echo "yes"
yes
[root@localhost shell]# [ -z ]&&echo "yes"
yes
[root@localhost shell]# [ -z hello ]&&echo "yes"
[root@localhost shell]# 

1.4逻辑测试

​ 格式1:[表达式1]操作符[表达式2]
​ 格式2:命令1操作符命令2 ...
常用的测试操作符
​ ●-a或&&:逻辑与,'而且”的意思
​ ●-o或||: 逻辑或,“或者” 的意思
​ ●!:逻辑否

实例参照上面的字符串测试实例即可。

五、if语句的结构

5.1单分支结构:

if 条件测试操作

​ then 命令序列

fi

5.2双分支结构

if 条件测试操作

​ then 命令序列1

​ else 命令序列2

fi

5.3多分支结构

if 条件测试操作1

​ then 命令序列1

elif 条件测试操作2

​ then 命令序列2

else

命令序列3

fi

六、case语句结构

结构格式:

case 变量值 in

模式1)

    命令序列1

    ;;

模式2)

    命令序列2

    ;;

*)

    默认命令序列

esac

总结:if条件判断一般是用于区间判断,case一般用于固定值或字符串判断。

推荐阅读:
  1. 全面了解Shell编程中的case语句与函数
  2. shell编程之case语句与循环语句

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

shelltestifcase he hell

上一篇:软件测试相关1

下一篇:TCPDF 如何实现首行缩进

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》