5

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?

2
  • a=$(./2.sh); r=$?; ## doesn't work?
    – Jeff Schaller
    Mar 4, 2016 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, 2018 at 14:20

1 Answer 1

10

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"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .