bash 中的 if 和 [[ 有什么区别?

bag*_*har 4 bash

我看到

if cmd
then
echo Hi
fi
Run Code Online (Sandbox Code Playgroud)

工作方式与

if [[ $(cmd) ]]
then
echo Hi
fi
Run Code Online (Sandbox Code Playgroud)

那么当有 [[ 而没有时会发生什么呢?

jor*_*anm 8

在 shell 中[是 test 命令的别名。这命令。这[[是一些 shell 的一个特性,只是略有不同。在 bash 中,它是一个关键字,而不是一个命令,但其功能类似于命令。

您可以这样想:您正在运行[[并提供“$(cmd)”的输出作为该命令的参数。if然后检查 的返回状态[[。当没有运算符被赋予[[,-n是隐含的。

   -n string
          True if the length of string is non-zero.
Run Code Online (Sandbox Code Playgroud)

对于您的示例:

if cmd          # check the return status of cmd
if [[ $(cmd) ]] # check if cmd has any output
Run Code Online (Sandbox Code Playgroud)