您的位置:首页 > 运维架构 > Shell

SHELL学习——退出状态、测试(整数\字符串\ 文件\逻辑运算符)

2012-12-18 17:22 459 查看
[align=left][/align]退出状态
在Linux系统中,第当命令执行完成后,系统都会有一个退出状态。该退出状态用一整数值表示,用于判断命令运行正确与否。
状态值
含义
0
表示运行成功,程序执行未遇到任何问题
1~125
表示运行失败,脚本命令、系统命令错误或参数传递错误
126
找到了该命令但无法执行
127
未找到要运行的命令
>128
命令被系统强行结束
举例说明:

[root@localhost tmp]# touch exit_exam1
[root@localhost tmp]# echo $?
0
[root@localhost tmp]# dddd
-bash: dddd: command not found
[root@localhost tmp]# echo $?
127
[root@localhost tmp]# rm 999
rm: cannot lstat `999': No such file or directory
[root@localhost tmp]# echo $?
1
[root@localhost tmp]#

测试
Linux的shell命中存在一组测试命令,该组命令用于测试某种条件或某几种条件是否真实存在。测试命令是判断语句和循环语句中条件测试的工具。
整数比较运算符(不适应浮点型数值比较)
整数比较运算符
描述
[align=left] [/align]
num1 –eq num2
如果num1=num2,测试结果为0
-eq
=
num1 –ge num2
如果num1>=num2,测试结果为0
-ge
>=
num1 –gt num2
如果num1>num2,测试结果为0
-gt
>
num1 –le num2
如果num1<=num2,测试结果为0
-le
<=
num1 –lt num2
如果num1<num2,测试结果为0
-lt
<
num1 –ne num2
如果num1!=num2,测试结果为0
-ne
!=
举例说明:

[root@localhost ~]# num1=15
[root@localhost ~]# [ "$num1" -eq 15 ]
[root@localhost ~]# echo $?
0
[root@localhost ~]# [ "$num1" -eq 20 ]
[root@localhost ~]# echo $?
1
[root@localhost ~]# first_num=99
[root@localhost ~]# second_num=100
[root@localhost ~]# [ "$first_num" -gt "$second_num" ]
[root@localhost ~]# echo $?
1

字符串运算符
字符串运算符
描述
string
测试字符串string是否不为空
-n string
测试字符串string是否不为空
-z string
测试字符串string是否为空
string1=string2
测试字符串string1是否与字符串string2相同
string1!=string2
测试字符串string1是否与字符串string2不相同
举例说明:

[root@localhost ~]# string1=""
[root@localhost ~]# test "$string1"
[root@localhost ~]# echo $?
1
[root@localhost ~]# test -n "$string1"
[root@localhost ~]# echo $?
1
[root@localhost ~]# test -z "$string1"
[root@localhost ~]# echo $?
0

文件操作符
文件运算符
描述
-d file
测试file是否为目录
-e file
测试file是否存在
-f file
测试file是否为普通文件
-s file
测试file的长度是否不为0
-r file
测试file是否是进程可读文件
-w file
测试file是否是进程可写文件
-x file
测试file是否是进程可执行文件
-L file
测试file是否符号化链接
举例说明:

[root@localhost ~]# ls
anaconda-ks.cfg Desktop install.log
install.log.syslog sshd_config
[root@localhost ~]# [ -d install.log ]
[root@localhost ~]# echo $?
1
[root@localhost ~]# [ -e install.log ]
[root@localhost ~]# echo $?
0
[root@localhost ~]# [ -e install1.log ]
[root@localhost ~]# echo $?
1
[root@localhost ~]# [ -w install.log ]
[root@localhost ~]# echo $?
0

逻辑运算符
逻辑运算各符
描述
! expression
如果expression为假,则测试结果为真
expression1 –a expression2
如果expression1和expression2同时为真,则测试结果为真
Expression1 –o expression2
如果expression1和expression2中有一个为真,则测试条件为真
逻辑运算的真假表
expr1
expr2
! expr1
! expr2
expr1 –a expr2
expr1 –o expr2
























举例说明:

[root@localhost ~]# ls
anaconda-ks.cfg Desktop install.log
install.log.syslog sshd_config
[root@localhost ~]# [ ! -e install.log ]
[root@localhost ~]# echo $?
1
#说明文件install.log不存在为假
[root@localhost ~]# [ -e install.log -a -r install.log ]
[root@localhost ~]# echo $?
0 #说明文件install.log存在且可读

[align=left] [/align]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  测试 运算符 退出
相关文章推荐