0

I have a Bash script fragment like this:

local SOME_VAR=$( first_command | second_command )
SECOND_COMMAND_EXIT_CODE=$?

But SECOND_COMMAND_EXIT_CODE is always zero even when second_command fails. It is also worth noting that second_command outputs multiple lines of text.

Is there a way to capture all the output of second_command in a variable and also capture its exit code in another variable?

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Jason Stangroome
  • 4,459
  • 3
  • 33
  • 39
  • FYI, all-uppercase variable names are by convention reserved for environment variables (if following the letter of POSIX, specifically for environment variables honored by system components -- see http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html, keeping in mind that shell variables and environment variables share a namespace) and builtins; others should contain at least one lower-case letter. – Charles Duffy May 26 '15 at 00:20
  • ...now, if you're doing something else (like logging) in your "real" code that isn't reflected here, that would be a believable alternate explanation; it's easy to mistakenly modify `$?` by adding extra commands, even if those commands are intended to be noops. – Charles Duffy May 26 '15 at 00:24

1 Answers1

1

Observe:

foo=$(echo "hello world" | false); foo_exit=$?
echo "$foo_exit"

...yields 1, not 0 as this question claims. Thus, the question's premise is false; if second_command fails without its exit status reflecting that, this is an issue to be brought up with its author/maintainer.


Per clarification in comments -- local is a builtin command, which, like other builtins, modifies $?. Thus, it's necessary to separate the commands to avoid modifying this value:

local foo
foo=$(echo "hello world" | false); foo_exit=$?
echo "$foo_exit"
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441