Shell 运算符

算术、关系、逻辑、字符串与文件测试运算符。

Beginner
Key Points算术用 $(( )) 或 (( )),比较字符串用 = 和 !=,比较数字用 -eq/-lt,文件用 -f/-d/-e。

算术运算

Bash
a=7
b=2
echo "$((a + b)) $((a - b)) $((a * b))"
echo "div=$((a / b)) mod=$((a % b))"
echo "pow=$((a ** 2))"
((a++))
echo "a=$a"
Output
9 5 14
div=3 mod=1
pow=49
a=8

字符串比较

Bash
x="abc"
y="abd"
[ "$x" = "$y" ] && echo "same" || echo "different"
[ "$x" \< "$y" ] && echo "x before y"
[ -z "" ] && echo "empty"
[ -n "$x" ] && echo "not empty"
Output
different
x before y
empty
not empty

数值比较

OperatorMeaning
-eq / -neEqual / not equal
-lt / -leLess than / less or equal
-gt / -geGreater than / greater or equal
Bash
n=10
if [ "$n" -ge 10 ]; then echo "n >= 10"; fi
if (( n > 5 )); then echo "n > 5"; fi
Output
n >= 10
n > 5

逻辑与文件测试

Bash
echo "hello" > demo.txt
f="demo.txt"
[ -f "$f" ] && echo "is file"
[ -r "$f" ] && echo "readable"
[ -d . ] && echo "is dir"
[ -f nope.txt ] || echo "missing"
[ -f "$f" -a -r "$f" ] && echo "file and readable"
Output
is file
readable
is dir
missing
file and readable
TestTrue when
-eExists
-f / -dRegular file / directory
-sExists and size > 0
-r / -w / -xReadable / writable / executable
-z / -nEmpty / non-empty string
[ is a command, so spaces are mandatory. [ $a=1 ] does not error; it is silently always true — one of the nastiest traps.

逻辑组合

Bash
true && echo "and"
false || echo "or"
! false && echo "not"
Output
and
or
not

Friends & Partners