记录shell中的数字与字符串比较操作用法

if的格式

注意格式:

1
2
3
if空格[空格$A空格==空格$B空格];then 
...
fi

空格一定要有,否则判断出错。

正确示例:

1
2
3
4
5
6
7
8
#!/bin/bash -x
A=1
B=2
if [ A == B ];then
echo "B"=$B
else
echo "A="$A
fi

输出A=1
错误示例:
1
2
3
4
5
6
7
8
#!/bin/bash -x
A=1
B=2
if [ A==B ];then
echo "B"=$B
else
echo "A="$A
fi

输出B=2

在shell中字符串与数值的比较方法不同

1、整数比较:

等于 -eq=
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/bash -x
if [ 5 = 3 ] ;then
echo "A"
else
echo "B"
fi
#output:B
if [ 3 -eq 3 ] ;then
echo "A"
else
echo "B"
fi
#output:A
不等于 -ne<>
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/bash -x
if [ 5 <> 3 ] ;then
echo "A"
else
echo "B"
fi
#output:A
if [ 3 -ne 3 ] ;then
echo "A"
else
echo "B"
fi
#output:B
大于 -gt>
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/bash -x
if (( 5 > 3 )) ;then
echo "A"
else
echo "B"
fi
#output:A
if [ 3 -gt 3 ] ;then
echo "A"
else
echo "B"
fi
#output:B
大于等于 -ge>=
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/bash -x
if (( 3 >= 5 ));then
echo "A"
else
echo "B"
fi
#output:B
if [ 3 -ge 3 ] ;then
echo "A"
else
echo "B"
fi
#output:A
小于 -lt<
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/bash -x
if (( 3 < 5 ));then
echo "A"
else
echo "B"
fi
#output:A
if [ 3 -lt 3 ] ;then
echo "A"
else
echo "B"
fi
#output:B
小于等于 -le<=
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/bash -x
if (( 5 <= 3 ));then
echo "A"
else
echo "B"
fi
#output:B
if [ 3 -le 3 ] ;then
echo "A"
else
echo "B"
fi
#output:A

2、字符串比较:

等于===

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/bin/bash -x
if [ "A" = "B" ] ;then
echo "A"
else
echo "B"
fi
#output:B
if [ "A" = "A" ] ;then
echo "A"
else
echo "B"
fi
#output:A
if [ "A" == "B" ] ;then
echo "A"
else
echo "B"
fi
#output:B
if [ "A" == "A" ] ;then
echo "A"
else
echo "B"
fi
#output:A

不等于 !=
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/bash -x
if [ "A" != "B" ] ;then
echo "A"
else
echo "B"
fi
#output:A
if [ "A" != "A" ] ;then
echo "A"
else
echo "B"
fi
#output:B

空串 -z
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/bash -x
if [ -z "A" ] ;then
echo "A"
else
echo "B"
fi
#output:B
if [ -z "" ] ;then
echo "A"
else
echo "B"
fi
#output:A

非空串 -n
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/bash -x
if [ -n "A" ] ;then
echo "A"
else
echo "B"
fi
#output:A
if [ -n "" ] ;then
echo "A"
else
echo "B"
fi
#output:B