4

I'd like to do:

1.sh:

#!/usr/bin/env bash
set -eu
r=0
a=$(./2.sh || r=$?)
echo "$a"
echo "$r"

2.sh:

#!/usr/bin/env bash
echo output
exit 2

But it outputs:

$ ./1.sh
output
0   # I'd like to have `2` here

Since $(...) runs a separate shell. So, how do I capture both, exit code and output?

  • a=$(./2.sh); r=$?; ## doesn't work? – Jeff Schaller Mar 4 '16 at 11:34
  • The reason 1.sh has an exit code of 0 not 2 is because echo "$r" is a command that exits 0. – Mikkel May 29 '18 at 14:20
9

The exit code of a process calling another process is the one of the called process.

$($($($($(exit 2)))))
echo $?
2

Here there are 5 levels of calling.

In your case:

r=0
a=$(./2.sh)
r=$?
echo "$a"
echo "$r"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.