Shell test 命令
test / [ / [[ 的差别、常用判断、字符串与数值陷阱。
Key Points优先用 [[ ]]:支持 && || 和正则匹配,且不会因变量为空而报错;[ ] 是外部命令,空格必须严格。
三种写法
Bash
test 1 -lt 2 && echo "test ok"
[ 1 -lt 2 ] && echo "[ ] ok"
[[ 1 -lt 2 ]] && echo "[[ ]] ok"Output
test ok
[ ] ok
[[ ]] ok| Form | Type | Supports &&/|| | Pattern match |
|---|---|---|---|
test | Command | No | No |
[ ] | Command (POSIX) | No | No |
[[ ]] | bash keyword | Yes | Yes, =~ |
字符串判断
Bash
s=""
[ -z "$s" ] && echo "empty"
[ -n "abc" ] && echo "non-empty"
[[ "hello" == he* ]] && echo "prefix match"
[[ "abc123" =~ ^[a-z]+[0-9]+$ ]] && echo "regex match"Output
empty
non-empty
prefix match
regex match数值判断
Bash
a=5
[ "$a" -gt 3 ] && echo "gt"
(( a == 5 )) && echo "eq"Output
gt
eqWhen
a is empty, [ $a -gt 3 ] becomes [ -gt 3 ] and errors with "unary operator expected". Quote the variable, or use (( a > 3 )).文件判断
Bash
echo "x" > a.txt
echo "y" > b.txt
touch -t 202601010000 a.txt # 把 a.txt 的时间设成 2026-01-01
[ -f a.txt ] && echo "file"
[ -d . ] && echo "dir"
[ -s a.txt ] && echo "not empty"
[ b.txt -nt a.txt ] && echo "b newer" || echo "b older-or-equal"Output
file
dir
not empty
b newer组合条件
Bash
a=1; b=2
[[ $a -eq 1 && $b -eq 2 ]] && echo "both"
[[ $a -eq 9 || $b -eq 2 ]] && echo "either"
[[ ! -f /nope ]] && echo "not exists"Output
both
either
not exists三种写法
Bash
test 1 -lt 2 && echo "test ok"
[ 1 -lt 2 ] && echo "[ ] ok"
[[ 1 -lt 2 ]] && echo "[[ ]] ok"Output
test ok
[ ] ok
[[ ]] ok| 写法 | 类型 | 支持逻辑符 | 模式匹配 |
|---|---|---|---|
test | 命令 | 否 | 否 |
[ ] | 命令(POSIX) | 否 | 否 |
[[ ]] | bash 关键字 | 是 | 是,=~ |
字符串判断
Bash
s=""
[ -z "$s" ] && echo "empty"
[ -n "abc" ] && echo "non-empty"
[[ "hello" == he* ]] && echo "prefix match"
[[ "abc123" =~ ^[a-z]+[0-9]+$ ]] && echo "regex match"Output
empty
non-empty
prefix match
regex match数值判断
Bash
a=5
[ "$a" -gt 3 ] && echo "gt"
(( a == 5 )) && echo "eq"Output
gt
eq[ $a -gt 3 ] 在 a 为空时会变成 [ -gt 3 ],报 unary operator expected。所以变量永远加引号:[ "$a" -gt 3 ],或者直接用 (( a > 3 ))。文件判断
Bash
echo "x" > a.txt
echo "y" > b.txt
touch -t 202601010000 a.txt # 把 a.txt 的时间设成 2026-01-01
[ -f a.txt ] && echo "file"
[ -d . ] && echo "dir"
[ -s a.txt ] && echo "not empty"
[ b.txt -nt a.txt ] && echo "b newer" || echo "b older-or-equal"Output
file
dir
not empty
b newer组合条件
Bash
a=1; b=2
[[ $a -eq 1 && $b -eq 2 ]] && echo "both"
[[ $a -eq 9 || $b -eq 2 ]] && echo "either"
[[ ! -f /nope ]] && echo "not exists"Output
both
either
not exists