Shell – Capture exit code and output of a command

command-substitutionexit-statusshell

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?

Best Answer

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"
Related Question