![unix测试何时在测试命令中使用eq vs = vs ==?](https://linux22.com/image/59668/unix%E6%B5%8B%E8%AF%95%E4%BD%95%E6%97%B6%E5%9C%A8%E6%B5%8B%E8%AF%95%E5%91%BD%E4%BB%A4%E4%B8%AD%E4%BD%BF%E7%94%A8eq%20vs%20%3D%20vs%20%3D%3D%EF%BC%9F.png)
我什么时候应该使用-eq
vs =
vs==
例如
[[ $num -eq 0 ]]
[[ $num = 'zzz' ]]
-eq
我观察到使用(and-ne
等) 表示数字和=
字符串的模式。这有什么原因吗?我应该什么时候使用==
答案1
因为那是这些操作数的定义。从POSIX 测试文档,OPERANDS 部分:
s1 = s2
如果字符串 s1 和 s2 相同,则为 True;否则为假。
...
n1-eq n2
如果整数 n1 和 n2 在代数上相等,则为 True;否则为假。
==
不是由 POSIX 定义的,它是 的扩展bash
,源自ksh
.==
当您想要便携性时不应该使用。从bash 文档 - Bash 条件表达式:
字符串1 == 字符串2
字符串1 = 字符串2
如果字符串相等则为 True。'=' 应与测试命令一起使用以确保 POSIX 一致性。
答案2
符号=
用于字符串比较,而-eq
用于整数比较。两者都与test
和 一起工作[...]
。如果您将bash
then 与语法一起使用[[...]]
,您也可以将其用于==
字符串比较。另外,在 bash=
和==
with中也[[...]]
适用patterns
(例如[[ $x == y* ]]
.
答案3
以下序列可以提供更详细的
帮助:
gnu:~$ [ sam -eq sam ]
bash: [: sam: integer expression expected
gnu:~$ echo "Exit status of \"[ sam -eq sam ]\" is $?."
Exit status of "[ sam -eq sam ]" is 2.
gnu:~$ [ 5 -eq 5 ]
gnu:~$ echo "Exit status of \"[ 5 -eq 5 ]\" is $?."
Exit status of "[ 5 -eq 5 ]" is 0.
gnu:~$ [ 5 = 5 ]
gnu:~$ echo "Exit status of \"[ 5 = 5 ]\" is $?."
Exit status of "[ 5 = 5 ]" is 0.
gnu:~$ [ sam = sam ]
gnu:~$ echo "Exit status of \"[ sam = sam ]\" is $?."
Exit status of "[ sam = sam ]" is 0.
gnu:~$ [ 5 == 5 ]
gnu:~$ echo "Exit status of \"[ 5 == 5 ]\" is $?."
Exit status of "[ 5 == 5 ]" is 0.
gnu:~$ [ sam == sam ]
gnu:~$ echo "Exit status of \"[ sam == sam ]\" is $?."
Exit status of "[ sam == sam ]" is 0.
gnu:~$ (( 5 == 5 ))
gnu:~$ echo "Exit status of \"(( 5 == 5 ))\" is $?."
Exit status of "(( 5 == 5 ))" is 0.
gnu:~$ (( sam == sam ))
gnu:~$ echo "Exit status of \"(( sam == sam ))\" is $?."
Exit status of "(( sam == sam ))" is 0.
gnu:~$ ( sam = sam )
The program 'sam' is currently not installed. You can install it by typing:
sudo apt-get install simon
gnu:~$ echo "Exit status of \"( sam = sam )\" is $?."
Exit status of "( sam = sam )" is 127.
gnu:~$ ( 5 = 5 )
5: command not found
gnu:~$ echo "Exit status of \"( 5 = 5 )\" is $?."
Exit status of "( 5 = 5 )" is 127.
gnu:~$ ( sam == sam )
The program 'sam' is currently not installed. You can install it by typing:
sudo apt-get install simon
gnu:~$ echo "Exit status of \"( sam == sam )\" is $?."
Exit status of "( sam == sam )" is 127.
gnu:~$ ( 5 == 5 )
5: command not found
gnu:~$ echo "Exit status of \"( 5 == 5 )\" is $?."
Exit status of "( 5 == 5 )" is 127.
答案4
从man test
:
-eq
, ETC。
接力算术测试。参数必须完全是数字(可能是负数),或者是特殊表达式“-l STRING”,其计算结果为 STRING 的长度。
STRING1 = STRING2
True if the strings are equal.
STRING1 == STRING2
True if the strings are equal (synonym for =).
所以=
和==
是同义词