hel hel - 1 year ago 60
Linux Question

What happens if a variable is assigned with command expression in backticks

Below is the code of bash:

a=`echo hello`
echo $a

output is :


But I think it should be:



Answer Source

You mistakenly think that a=`echo hello`:

  • executes echo hello and prints its stdout output directly to the caller's stdout.
  • and then assigns the exit code (return value) of the echo command to variable $a.

Neither is true; instead:

  • echo hello's stdout output is captured in memory (without printing to stdout - that's how command substitutions work)
  • and that captured output is assigned to $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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download