为什么bash的-c"虚假的;回声$&QUOT?;打印0? [英] Why does bash -c "false; echo $?" print 0?

查看:176
本文介绍了为什么bash的-c"虚假的;回声$&QUOT?;打印0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建设,尝试到服务器(通过SSH)上运行某些命令,以及他们是否成功在屏幕上写的脚本。

I'm building a script that tries to run some commands on a server (over SSH), and writes on the screen whether they were successful.

我注意到了 $?一个奇怪的现象,即不是在previous命令失败 0

I noticed a strange behaviour for $?, namely not being 0 when the previous command failed.

起初,我有:

ssh <user>@<server> <<EOF
    false
    if [ $? -ne 0 ]; then
        echo "It failed"
    else
        echo "It worked"
    fi
EOF

如果我复制和粘贴&LT内部脚本;&LT; EOF EOF ,它打印它失败。。如果我用 SSH运行的一部分,它打印它的工作。为了简化,我又试图:

If I copy and paste the script inside <<EOF and EOF, it prints It failed. If I run it with the ssh part, it prints It worked. To simplify, I then tried:

ssh <user>@<server> <<EOF
    false
    echo $?
EOF

同样的事情发生。如果我复制粘贴或键入内部的命令,它打印 1 ,但如果我跑这一切(包括 SSH ),它打印 0

Same thing happened. If I copy-paste or type the commands inside, it prints 1, but if I run all of it (including the ssh), it prints 0.

如果我直接使用bash同样的错误发生这样

The same error happens if I directly use bash this way

bash <<EOF
    false
    echo $?
EOF

bash -c "false; echo $?"

为什么会出现这种情况?我如何检查previous命令在这方面失败了?

Why does this happen? How can I check if the previous command failed in this context?

推荐答案

这是因变量扩展。当你写的bash -c假;回声$该变量的命令之前跑扩大。所以,你的命令酷似的bash -c假;回声0;如果你的previous命令成功

This is due to variable expansion. When you write bash -c "false; echo $?" the variable is expanded before the commands are ran. So your command is exactly like bash -c "false; echo 0;" if your previous command was successful.

要拥有正确的结果,尝试的bash -c'假的;回声$?。这prevents变量扩展,将跨时preTED扩大。

To have the right result try bash -c 'false; echo $?'. This prevents variable expansion, it will be expanded when interpreted.

有关的文件在这里做的版本:

For the here document version do:

bash << 'EOF'
false
echo $?
'EOF'

在这种情况下,你需要引用在这里文件的分隔符。但要注意,你必须使用语法是用来输入命令的shell的语法。在这个例子中,我在的tcsh ,它需要使用完全相同的开幕式和闭幕式的分隔符。在庆典,收盘分隔符必须引用删除后开幕的。

In this case you need to quote the delimiter of the here document. But beware that the syntax you must use is the syntax for the shell you use to type the command. In the example, I was in tcsh , and it requires to use the exact same opening and closing delimiter. Under bash, the closing delimiter must be the opening one after quote removal.

这篇关于为什么bash的-c&QUOT;虚假的;回声$&QUOT?;打印0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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