Reputation: 43
Why do the following two commands produce different results?
$ bash -c "ls BLAH; echo $?; export status=$?; echo $status"
ls: cannot access BLAH: No such file or directory
0
^ note the empty line after 0
$ cat test.sh
ls BLAH; echo $?; export status=$?; echo $status
$ bash test.sh
ls: cannot access BLAH: No such file or directory
2
0
Upvotes: 1
Views: 58
Reputation: 225072
The expansions of $?
and $status
in your first example are done by your current shell - that is before the bash
you're running ever sees the command string. Use single quotes:
$ bash -c 'ls BLAH; echo $?; export status=$?; echo $status'
ls: BLAH: No such file or directory
1
0
or otherwise:
$ bash -c "ls BLAH; echo \$?; export status=\$?; echo \$status"
ls: BLAH: No such file or directory
1
0
Upvotes: 1