shell条件语句

从退出$?状态说起

linux命令执行完以后,会返回一个退出状态码来标识运行是否成功。如果退出状态码是0,则为成功,其它的数字都是不成功的。

$ ls
Applications	Desktop		Downloads	Movies		Pictures	Sites
Demos		Documents	Library		Music		Public		Workspace
$ echo $?
0

此时的$?的值是0,说明ls命令正确执行了

$ ls NotExistFolder
ls: NotExistFolder: No such file or directory
$ echo $?
1

此时的$?的值是1,说明ls命令没有正确执行

不仅是ls命令,每一个命令执行完以后,都可以通过$?来检查是否正确执行

test命令

本篇要谈的是shell中的条件语句,所谓的条件语句简单来讲就是:当某条件为真时,执行xxx,否则,执行xxx,而test命令是用来测试一个表达式的,它的格式一般是这样的:

test expression

其中,expression是待测试的条件。先来看个例子

$ name=Tom
$ test $name = Tom
$ echo $?
0
$ test $name = Lucy
$ echo $?
1

上面测试的是字符串是否相等。

注意,使用变量名时用双引号引起来是一个比较好的习惯,例如

$ test "$name" = Lucy

否则,当$name等于空字符串时,可能会改变程序员的本意

字符串操作符

上面的=就是一个简单的字符串操作符,除此以外,再来看看还有什么内建的字符串操作符

操作符 如果满足下列条件,则返回真(退出码为0)
string1 = string2 string1 等于 string2
string1 != string2 string1 不等于 string2
string1 string1不为空
-n string1 string1不为空
-z string1 string1 为空
$ name=Tom
$ test "$name" =  "Tom"					# 字符串等于
$ echo $?
0
$ test "$name" !=  "Tom"					# 字符串不等于
$ echo $?
1
$ test "$name" 								# 字符串不为空
$ echo $?
0
$ test -z "$name" 							
$ echo $?
1

整数操作符

操作符 如果满足下列条件,则返回真(退出码为0)
int1 -eq int2 int1 等于 int2
int1 -ge int2 int1 大于或等于 int2
int1 -gt int2 int1 大于 int2
int1 -le int2 int1 小于或等于 int2
int1 -lt int2 int1 小于 int2
int1 -ne int2 int1 不等于 int2
$ test 2 -gt 1
$ echo $?
0
$ test 2 -le 2
$ echo $?
0
$ test 2 -le 1
$ echo $?
1

test的另一种形式

test命令的另一种形式是

[ expression ]

注意expression左右都是有空格的。

举个例子看下

$ name=Tom
$ [ "$name" = Tom ] 
$ echo $?
0
$ [ 2 -gt 3 ]
$ echo $?
1

文件操作符

shell还内置了一些针对文件的操作符,可以很方便的用来和文件打交道。

操作符 如果满足下列条件,则返回真(退出码为0)
-d file file 是一个目录
-e file file 存在
-f file file 是一个普通文件
-s file file 不是空文件
-r file file 可被读取
-w file file 可被写入
-x file file 可被执行
-L file file 是一个符号链接
$ touch 1.txt   # 新建一个文件
$ [ -e 1.txt ]  # 文件是否存在?是
$ echo $?       
0
$ [ -r 1.txt ]  # 文件是否可被读取?是
$ echo $?
0
$ [ -s 1.txt ]  # 文件是否不为空?否
$ echo $?
1

逻辑操作符:not, and, or

  • 逻辑非(not) !
  • 逻辑与(and) -a
  • 逻辑或(or) -o
$ [ -e 1.txt ]  # 文件是否存在?是
$ echo $?       
0
$ [ ! -e 1.txt ]  # 文件不存在?否
$ echo $?
1
$ [ -r 1.txt -a -w 1.txt ] # 文件可读且可写?是
$ echo $?
0

你可能感兴趣的:(linux,shell脚本编程)