unix測試何時在測試指令中使用eq vs = vs ==?

unix測試何時在測試指令中使用eq vs = vs ==?

我什麼時候應該使用-eqvs =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和 一起工作[...]。如果您將bashthen 與語法一起使用[[...]],您也可以將其用於==字串比較。另外,在 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 =).

所以===是同義詞

相關內容