Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

There are similar questions, but mine is a little bit different. Or so I think. What I'd like to do is:

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 separate shell. So, how do I capture both, exit code and output?

share|improve this question
    
a=$(./2.sh); r=$?; ## doesn't work? – Jeff Schaller Mar 4 '16 at 11:34
up vote 5 down vote accepted

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"
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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