无法在bash中的双括号中执行命令 [英] Does not work to execute command in double brackets in bash

查看:59
本文介绍了无法在bash中的双括号中执行命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In an attempt to stay consistent i have tried to use double brackets [[ ]] in all my if statements. I did however get into a problem when i was going to check the return value for a command i wanted to run. After testing several ways of creating an if statement i found that only without brackets could i execute a command.

以下内容无效:

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

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

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

和上面的代码使if循环为true,即使未运行该命令也是如此.由于上面的代码不适用于花括号,因此无法使用以下任一方法:

and the code above makes the if loop true even when the command was not run. since the code above doesnt work with braces it doesnt work to use this either:

[[ $command ]] || echo "failed"

,它也不能在子shell中工作.

and it doesnt work in a subshell either.

以下作品:

if $command ; then
    echo "something"
fi

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

为什么将命令放在带括号的if循环中不起作用,为什么即使没有运行命令,上述if循环也报告为true?我正在使用bash版本4.1.9.我已经尝试了很多次,并且if循环与我在上面键入的循环一样简单,它只是检查命令是否成功运行,如果没有成功则退出.

Why doesnt it work to place a command in an if loop with brackets, and why does the if loops above report true when it didnt even run the command ? I'm using bash version 4.1.9. Ive tried this many times and the if loops are just as simple as the ones i typed above, it just checks if a command was run successfully and exits if it wasnt.

推荐答案

简短的答案是:

  • [ [[]期望表达式.

如果需要一个命令.

说:

[[ $(command) ]]

实际上将执行:

[[ -n <command_output> ]]

可能不是您想要的.另一方面,说:

which may or may not be what you want. On the other hand, saying:

$command && echo something || echo other

将根据命令的返回码(分别为 0 和非零)回显某物 other .

would echo something or other based on the return code of the command (0 and non-zero respectively).

这篇关于无法在bash中的双括号中执行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆