Bash 中的方括号和双括号有什么区别?

Bash 中的方括号和双括号有什么区别?

我注意到在这个问题一位回答者使用双括号,而另一位回答者使用方括号:

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

相关内容