我注意到在這個問題一位回答者使用雙括號,而另一位回答者則使用方括號:
if (( $(fileSize FILE1.txt) != $(fileSize FILE2.txt) )); then
…
if [ $(fileSize FILE1.txt) != $(fileSize FILE2.txt) ]; then
我以前沒見過雙括號 - 谷歌搜尋也沒有幫助。它們的意義完全相同嗎?便攜性有什麼差別嗎?優先選擇其中一個的理由是什麼?
答案1
從bash
線上說明頁:
((expression))
The expression is evaluated according to the rules described below under ARITHMETIC EVALUATION. If the value of the expression is
non-zero, the return status is 0; otherwise the return status is 1. This is exactly equivalent to let "expression".
[[ expression ]]
Return a status of 0 or 1 depending on the evaluation of the conditional expression expression. Expressions are composed of the
primaries described below under CONDITIONAL EXPRESSIONS. Word splitting and pathname expansion are not performed on the words
between the [[ and ]]; tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process sub‐
stitution, and quote removal are performed. Conditional operators such as -f must be unquoted to be recognized as primaries.
例如,您可以用來(( ))
執行數學比較和位元比較,以及[[ ]]
執行更抽象的比較(與)test file attributes and perform string and arithmetic comparisons
touch test;
if [ -e test ]; then
echo test exists
else
echo test does not exist
fi