Below is the code of bash:
a=`echo hello`
echo $a
output is :
hello
But I think it should be:
hello
0
Below is the code of bash:
a=`echo hello`
echo $a
output is :
hello
But I think it should be:
hello
0
You think wrong ;-)
Putting the command in backticks assigns the output (stdout) from the expression on the right to the variable on the left.
$?
gives you the "output status" (or return code) of the command - aka the "0" you were expecting.
So:
a=`echo hello`
Runs the command "echo hello" but instead of echoing to stdout, it "echoes" to varaiable a
. So a=whatever_the_command_would_have_written_to_stdout (in this case "hello") - nothing is actually written to stdout because it is "captured" by the ``s
You mistakenly think that a=`echo hello`
:
echo hello
and prints its stdout output directly to the caller's stdout,echo
command to variable $a
.Neither is true; instead:
echo hello
's stdout output is captured in memory (without printing to the caller's stdout; that's how command substitutions work),$a
.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.
As this [ this ] answer already mentioned, the return value for the last executed command is stored in
$? # ${?} is sometimes needed
If you wish a
to contain 'hello' and the return value of echo hello
in separate lines, ie
hello
0
below is one way to do it
$ a=`echo -en "hello\n" && echo -n $?` # here $? is ret val for 1st echo
$ echo -e "$a"
hello
0
Note
-n
with echo
suppresses the trailing new line-e
with echo
interprets escape sequences&&
is the logical and operator, the second echo
wouldn't have been executed had the first echo
failedAnother important point to note is that even the assignment ie
a=b
has a return value.