UNIX测试何时在测试命令中使用eq vs = vs ==?


22

我什么时候应该使用-eqvs =vs==

例如

[[ $num -eq 0 ]]

[[ $num = 'zzz' ]]

我观察到了使用-eq(和-ne等)数字和=字符串的模式。是否有这个原因,什么时候应该使用==

Answers:


24

因为那是这些操作数的定义。从POSIX测试文档中,“操作数”部分

s1 = s2

如果字符串s1和s2相同,则为true;否则为true。否则为假。

...

n1 -eq n2

如果整数n1和n2代数相等,则为true;否则为true。否则为假。

==不是由POSIX定义的,它是的扩展bash,从继承而来ksh==当您想要便携性时,您不应该使用。从bash文档-Bash条件表达式

字符串1 ==字符串2

字符串1 =字符串2

如果字符串相等,则为真。为测试POSIX一致性,应将'='与test命令一起使用。


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.  

2

来自man test

-eq

中继到算术测试。参数必须全部为数字(可能为负),或特殊表达式“ -l STRING”,其计算结果为STRING的长度。

STRING1 = STRING2

 True if the strings are equal.

STRING1 == STRING2

 True if the strings are equal (synonym for =).

所以===是同义词


2

Symbol =用于字符串比较,而-eq用于整数比较。都可与test和一起使用[...]。如果您正在使用bashthen语法[[...]],则还可以==用于字符串比较。此外,在庆典=,并==[[...]]对工作patterns太(作为例子[[ $x == y* ]]

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.