Actually, it's more the:
bash: nonsense: command not found
$ echo "$?"
That is surprising here.
bash to run the command that results of the split+glob operator on the stdout of
nonsense produces no output, it runs no command, so you may think the exit status should be 0.
But actually, when a simple command line has no argument, only assignment or redirection, the exit status is that of the last command substitution in assignment and normal words (not in redirection targets) that was run (though failure in redirections will also affect the exit status).
That's specially useful with assignments.
output=$(grep pattern file)
You can get both the output and exit status of
grep, which you couldn't do if
$? was otherwise the exit status of that non-command.
That is where there are both assignment words and argument words, the exit status of
cmd1 is ignored.
$? will contain the exit status of
$output will only be set for
cmd2 only. Exception to that is when
cmd2 is a special builtin.
eval is such a special builtin.
$ a=0; a=1 eval; echo "$a"
bash and most modern POSIX shells.
a=`exit 5` eval; echo "$?"
eval `exit 5`; echo "$?"
Would output 0, as it's the result of running
eval with no argument. But that was not the case in the Bourne shell or ksh88, where for special builtins you'd get the exit status of
exit 5 there.
In those shells, you'll also find:
$ a=`exit 3` set x; echo "$?"
set is another special builtin.
. is another special builtin. In the Bourne shell and ksh88:
$ . /some/file `exit 4`; echo "$?"
(as long as
/some/file doesn't run any command)