退出状态
在Linux系统中,每当命令执行完成后,系统都会返回一个退出状态,该退出状态用一整数表示,状态值为0,表示命令运行成功,不为0时表示运行失败。最后一次执行命令的退出状态被曝存在内置变量"$?"中,可以通过echo语句测试命令是否运行成功。
退出状态以及含义
状态值 | 含义 |
0 | 表示运行成功 |
1~125 | 运行失败,脚本命令、系统命令错误或者参数传递错误 |
126 | 找到该命令但无法执行 |
127 | 未找到要运行的命令 |
>128 | 命令被系统强制结束 |
ls
111.csv anaconda-ks.cfg home
echo $?
0
# 访问的目录不存在
ll tt
ls: 无法访问tt: 没有那个文件或目录
echo $?
2
#执行的命令不存在
fkjng
-bash: fkjng: 未找到命令
[root@localhost ~]# echo $?
127
测试
测试结构
测试命令用于测试表达式的条件的真假,如果测试条件为真则返回0,如果测试条件为假,返回非0,。
两种格式:
test expression
[ expression ]
整数比较运算符
test测试数值时有一整套比较运算符,格式:
test "num1" numeric_operator "num2"
或者[ "num1" numeric_operator "num2" ]
整数比较运算符 | 描述 |
-eq | 等于 |
-ge | 大于等于 |
-gt | 大于 |
-le | 小于等于 |
-lt | 小于 |
-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 ~]# [ "$num1" -gt 15 ]
[root@localhost ~]# echo $?
1
#运算符点数 需要特定的函数
[root@localhost ~]# [ 1.5 -lt 2.2 ]
-bash: [: 1.5: 期待整数表达式
字符串运算符
字符串运算符 | 描述 |
string | 测试是否不为空 |
-n string | 是否不为空 |
-z string | 是否为空 |
string1=string2 | 两个字符串是否相等 |
string1!=string2 | 是否不相等 |
[root@localhost ~]# str1=""
[root@localhost ~]# test "$str1"
[root@localhost ~]# echo $? # 该字符串为空
1
[root@localhost ~]# test -n "$str1"
[root@localhost ~]# echo $? # 该字符串为空
1
[root@localhost ~]# test -z "$str1"
[root@localhost ~]# echo $? # 该字符串为空
0
文件操作符
格式:test file_operator File
或者[ file_operator file ]
文件运算符 | 描述 |
-d | 是否为目录 |
-e | 是否存在 |
-f | 是否为普通文件 |
-r | 是否是进程可读文件 |
-s | 文件长度是都不为0 |
-w | 是否是进程可写文件 |
-x | 是否是进程可执行文件 |
-L | 是否符号化链接 |
[ -d dialer-service.conf ]
[root@localhost demo]# echo $?
1
[root@localhost demo]# [ -d test ]
[root@localhost demo]# echo $?
0
逻辑运算符
逻辑运算符 | 描述 |
!expression | 表达式真假 |
-a | 相当于与 |
-o | 相当于或 |
判断
简单if结构
if expression
then
command
command
fi
exit命令
exit status
if/else结构
if expression
then
command
else
command
fi
if/else 语句嵌套
if expression1
then
if expression2
then
command
else
command
fi
else
if expression3
then
command
command
else
command
fi
fi
if/elif/else结构
if expression1
then
command
elif expression2
then
command
elif expression3
then
command
else
command
fi
case结构
case variable in
value1)
command
...
command;;
value2)
command
...
command;;
valueN)
command
...
command;;
esac
运算符
和编译语言一样
数字常量
#!/bin/bash
# 默认十进制
let "num1=40"
echo "num1=$num1"
#八进制表示
let "num2=040"
echo "num2=$num2"
#十六进制表示
let "num3=0x40"
echo "num3=$num3"
[root@localhost demo]# ./constant_exam1.sh
num1=40
num2=32
num3=64
还可以用num#
来表示不同进制