shell脚本中test判断用法

1.test基本用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 等价写法
if test condition; then
# 条件为真时执行
fi

# 简写形式(常用)
if [ condition ]; then
...
fi

# 更安全的写法(注意空格)
if [[ condition ]]; then
...
fi

2.常见测试类型

文件测试

1
2
3
4
5
6
test -f file.txt        # 文件存在且是普通文件
test -d dir/ # 目录存在
test -e file # 文件存在(任意类型)
test -r file # 文件可读
test -w file # 文件可写
test -x file # 文件可执行

字符串比较

1
2
3
4
test -z "$var"          # 字符串为空
test -n "$var" # 字符串非空
test "$a" = "$b" # 字符串相等
test "$a" != "$b" # 字符串不等

整数比较

1
2
3
4
5
6
test $a -eq $b          # 相等
test $a -ne $b # 不等
test $a -gt $b # 大于
test $a -ge $b # 大于等于
test $a -lt $b # 小于
test $a -le $b # 小于等于

逻辑组合

1
2
3
test condition1 -a condition2   # 与 (AND)
test condition1 -o condition2 # 或 (OR)
test ! condition # 非 (NOT)

3.推荐写法

1
2
3
4
5
6
7
8
9
# 推荐:使用 [[ ]](bash/zsh),支持 && || 和通配符
if [[ -f config.json && -r config.json ]]; then
echo "config exists and is readable"
fi

# 推荐:字符串比较用 ==
if [[ "$name" == "admin" ]]; then
echo "Hello admin"
fi