0

Why do the following commands produce different output?

false ; echo $?
output: 1
bash -c "false ; echo $?"
output: 0

Both echo $SHELL and bash -c "echo $SHELL" return /bin/bash so I am not sure why the commands would differ in output.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Note that if you run `bash -c 'false; echo $?'; echo $?` you will get `1` and `0` output. That's because `bash` exits with the status of the last command executed, and the `echo` succeeds. Also `false; bash -c "false; echo $?"; echo $?` reports `1` and `0` — and if immediately followed by `bash -c "false; echo $?"` produces `0` as reported. – Jonathan Leffler Aug 12 '21 at 23:35
  • Note that `echo $$; bash -c "echo $$"` echoes the same value twice, whereas `echo $$; bash -c 'echo $$'` echoes two different values. – Jonathan Leffler Aug 12 '21 at 23:37

1 Answers1

1

Since the argument to bash -c is in double quotes, the original shell performs variable substitution in it. So you're actually executing

bash -c "false; echo 0"

Change it to single quotes and you'll get the output you expect.

bash -c 'false; echo $?'

See Difference between single and double quotes in Bash

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • That's assuming the previous command (before `bash -c ...`) succeeded. If it failed, you'll see that exit status, e.g. `false; bash -c "true ; echo $?"` will print "1". – Gordon Davisson Aug 13 '21 at 01:57
  • @GordonDavisson Since the OP got `0` output, it obviously did succeed. – Barmar Aug 13 '21 at 13:37