Why does bash -c “false; echo $?” print 0?

后端 未结 1 1776
清歌不尽
清歌不尽 2020-12-21 06:57

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.

I noticed a strange behaviour f

相关标签:
1条回答
  • 2020-12-21 07:27

    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.

    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'
    

    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.

    0 讨论(0)
提交回复
热议问题