Below is the code of bash:
You mistakenly think that
echo helloand prints its stdout output directly to the caller's stdout.
echocommand to variable
Neither is true; instead:
echo hello's stdout output is captured in memory (without printing to stdout - that's how command substitutions work)
A command's exit code (a return value indicating success vs. failure) is never directly returned in POSIX-like shells such as Bash.
The only way to use an exit code is either:
explicitly, by accessing special variable
$? immediately after the command (
$? contains the most recent command's exit code)
implicitly, in conditionals (a command whose exit code is
0 evaluates to true in a conditional, any other exit code implies false).
Thus, to achieve what you're really trying to do, use:
echo 'hello' # Execute a command directly (its stdout output goes to the caller's stdout) a=$? # Save the previous command's exit code in var. $a echo "$a" # Echo the saved exit code.