Capture exit code and output of a command
18,648
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 videos on Youtube
Author by
x-yuri
Updated on September 18, 2022Comments
-
x-yuri almost 2 years
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?-
Admin about 6 yearsThe reason
1.sh
has an exit code of 0 not 2 is becauseecho "$r"
is a command that exits 0.
-