我什么时候应该使用-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 =).
所以=
和==
是同义词