Shell test 命令

test / [ / [[ 的差别、常用判断、字符串与数值陷阱。

Beginner
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
FormTypeSupports &&/||Pattern match
testCommandNoNo
[ ]Command (POSIX)NoNo
[[ ]]bash keywordYesYes, =~

字符串判断

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
When 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

Friends & Partners