天天看点

Linux-Shell脚本编程-学习-5-Shell编程-使用结构化命令-if-then-else-elif

if-then语句格式如下

Linux-Shell脚本编程-学习-5-Shell编程-使用结构化命令-if-then-else-elif

bash shell中的if语句可鞥会和我们接触的其他if语句的工作方式不同,bash shell的if语句会运行if语句后面的那个命令,如果该命令的退出状态码是0 那么执行位于then部分的的命令。

代码实例

Linux-Shell脚本编程-学习-5-Shell编程-使用结构化命令-if-then-else-elif

这个脚本的功能就是,执行date命令,如果date命令执行成功,那么他的退出状态码是0就执行then后面的代码,在屏幕上面输一行文字,this is the if-then test

then后面的语句可以是一条或多条,和我们写简单的shell脚本没有区别,这里会一条一条的执行下去

测试实例代码

Linux-Shell脚本编程-学习-5-Shell编程-使用结构化命令-if-then-else-elif

如果我们想要在shell和我们平常一样使用if else的功能,我们需要使用一下命令格式

Linux-Shell脚本编程-学习-5-Shell编程-使用结构化命令-if-then-else-elif

这里,如果 执行if后面的命令的退出状态码是0 就执行then后面的代码块,否则就执行else后面的代码块

测试代码

Linux-Shell脚本编程-学习-5-Shell编程-使用结构化命令-if-then-else-elif

在shell编程中,也是有if嵌套的,使用格式如下

Linux-Shell脚本编程-学习-5-Shell编程-使用结构化命令-if-then-else-elif

这个就没有实例代码了,如果有兴趣的,可以吧上面的代码改吧改吧试试看,每次只能测试一种。

好了,学习下一个命令,test

test是个好东西,他的功能之一就是可以是我们shell的if可以比较真假的,test的基本命令格式很简单

Linux-Shell脚本编程-学习-5-Shell编程-使用结构化命令-if-then-else-elif

condition是test命令要测试的一系列参数和值,当用在if-then语句的时候,test命令执行,如果tets命令中列出的条件为真的时候,退出状态码为0 否则为1,这样就可以在if-then中使用了

就是下面的格式了

Linux-Shell脚本编程-学习-5-Shell编程-使用结构化命令-if-then-else-elif

不过每次这么写也挺别扭的。所以,在bash中,提供了另外一种tets的写法,那就是方括号[]

不过必须要在左方括号右面,右方括号左面各加一个空格才可以,不然报错

Linux-Shell脚本编程-学习-5-Shell编程-使用结构化命令-if-then-else-elif

test命令可以判断三种类型条件

1. 数值比较

2. 字符串比较

3. 文件比较

第一类,test数值比较的基本功能

Linux-Shell脚本编程-学习-5-Shell编程-使用结构化命令-if-then-else-elif
Linux-Shell脚本编程-学习-5-Shell编程-使用结构化命令-if-then-else-elif
Linux-Shell脚本编程-学习-5-Shell编程-使用结构化命令-if-then-else-elif

第二个儿问题

#!/bin/bash

#testing string sort order

val1=testing

val2=Testing

if [ $val1 \> $val2 ]

   then

   echo "$val1 is greater than $val2"

else

   echo "$val1 is less than $val2"

fi

字符串大小

#testing string length

val2=''

if [ -n "$val1" ]

   echo "the string '$val1' is not empty"

   echo "the string '$val1' is empty"

if [ -z "$val2" ]

   echo "the string '$val2' is empty"

   echo "the string '$val2' is not empty"

后面还有文件的比较,由于文件比较内容比较多,我会在写一个。

Linux-Shell脚本编程-学习-5-Shell编程-使用结构化命令-if-then-else-elif