无法在 bash 中执行双括号中的命令

5 linux bash shell

为了保持一致,我尝试在所有 if 语句中使用双括号 [[ ]]。然而,当我要检查我想要运行的命令的返回值时,我确实遇到了问题。在测试了几种创建 if 语句的方法之后,我发现只有没有括号才能执行命令。

以下不起作用:

if [[ $command ]] ; then
    echo "something"
fi

if [[ $(command) ]] ; then
    echo "something"
fi

if [[ ${command} ]] ; then
    echo "something"
fi
Run Code Online (Sandbox Code Playgroud)

即使命令未运行,上面的代码也会使 if 循环为 true。由于上面的代码不适用于大括号,因此使用它也不起作用:

[[ $command ]] || echo "failed"
Run Code Online (Sandbox Code Playgroud)

它也不能在子 shell 中工作。

以下作品:

if $command ; then
    echo "something"
fi

if $(command) ; then
    echo "something"
fi
Run Code Online (Sandbox Code Playgroud)

为什么将命令放入带括号的 if 循环中不起作用,为什么上面的 if 循环在甚至没有运行该命令时报告 true ?我使用的是 bash 版本 4.1.9。我已经尝试了很多次,if 循环就像我上面输入的一样简单,它只是检查命令是否成功运行,如果没有成功则退出。

dev*_*ull 6

简短的回答是:

  • [并[[期待一个表情。

  • if等待命令。

说:

[[ $(command) ]]
Run Code Online (Sandbox Code Playgroud)

本质上会执行:

[[ -n <command_output> ]]
Run Code Online (Sandbox Code Playgroud)

这可能是也可能不是您想要的。另一方面又说:

$command && echo something || echo other
Run Code Online (Sandbox Code Playgroud)

将回显something或other基于命令的返回代码(0分别为非零)。