#《快乐的 Linux 命令行》

#字符串表达式

表达式 返回true的条件
string string不为null[1]
-n string 字符串string的长度大于零
-z string 字符串string的长度为零
string1 = string2 string1string2相同
string1 == string2 string1string2相同
string1 != string2 string1string2不相同
string1 > string2 string1排列在string2之后
string1 < string2 string1排列在string2之前

当与test一块使用的时候,><表达式操作符必须用引号引起来,或者是用反斜杠转义。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/bin/bash

# test-string: evaluate the value of a string

ANSWER=maybe
if [ -z "$ANSWER" ]; then
echo "There is no answer." >&2
exit 1
fi
if [ "$ANSWER" = "yes" ]; then
echo "The answer is YES."
elif [ "$ANSWER" = "no" ]; then
echo "The answer is NO."
elif [ "$ANSWER" = "maybe" ]; then
echo "The answer is MAYBE."
else
echo "The answer is UNKNOWN."
fi
1
2
$ ./test-string.sh
The answer is MAYBE.

#整型表达式

表达式 返回true的条件
integer1 -eq integer2 integer1等于integer2
integer1 -ne integer2 integer1不等于integer2
integer1 -le integer2 integer1小于或等于integer2
integer1 -lt integer2 integer1小于integer2
integer1 -ge integer2 integer1大于或等于integer2
integer1 -gt integer2 integer1等于integer2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/bin/bash

# test-integer: evaluate the value of an integer.

INT=-5
if [ -z "$INT" ]; then
echo "INT is empty." >&2
exit 1
fi
if [ $INT -eq 0 ]; then
echo "INT is zero."
else
if [ $INT -lt 0 ]; then
echo "INT is negative."
else
echo "INT is positive."
fi
if [ $((INT % 2)) -eq 0 ]; then
echo "INT is even."
else
echo "INT is odd."
fi
fi
1
2
3
$ ./test-integer.sh
INT is negative.
INT is odd.

好像所有的shell变量都是字符串类型,所以用不用引号好像没区别。

11:08:42

393/505


  1. 感觉这个没有卵用,我不管测试什么都是真。。。 ↩︎