Shell 运算符
算术、关系、逻辑、字符串与文件测试运算符。
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数值比较
| Operator | Meaning |
|---|---|
-eq / -ne | Equal / not equal |
-lt / -le | Less than / less or equal |
-gt / -ge | Greater than / greater or equal |
Bash
n=10
if [ "$n" -ge 10 ]; then echo "n >= 10"; fi
if (( n > 5 )); then echo "n > 5"; fiOutput
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| Test | True when |
|---|---|
-e | Exists |
-f / -d | Regular file / directory |
-s | Exists and size > 0 |
-r / -w / -x | Readable / writable / executable |
-z / -n | Empty / 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算术运算
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数值比较
| 运算符 | 含义 |
|---|---|
-eq/-ne | 等于 / 不等于 |
-lt/-le | 小于 / 小于等于 |
-gt/-ge | 大于 / 大于等于 |
Bash
n=10
if [ "$n" -ge 10 ]; then echo "n >= 10"; fi
if (( n > 5 )); then echo "n > 5"; fiOutput
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| 测试 | 为真条件 |
|---|---|
-e | 存在 |
-f/-d | 普通文件 / 目录 |
-s | 存在且非空 |
-r/-w/-x | 可读 / 可写 / 可执行 |
-z/-n | 空串 / 非空串 |
[ ] 是命令不是语法,所以 [ 后面、] 前面必须有空格。[ $a=1 ] 不会报错,但会永远为真——这是最难发现的坑之一。逻辑组合
Bash
true && echo "and"
false || echo "or"
! false && echo "not"Output
and
or
not