TheEmptyHour
TheEmptyHour

Reputation: 1

Getting exit code out of multiple commands in an assignment

Say I have a command that looks similar to the following:

VAR=$(python SomeScript | tee /dev/null)

I would like to get the exit code of python script but not really sure how with the assignment being in the same command.

Upvotes: 0

Views: 130

Answers (2)

that other guy
that other guy

Reputation: 123460

If you only have a single exit code to return, you can extract and exit with it to make that the exit code of the whole command substitution:

var=$(
  python -c 'import sys; print("hi"); sys.exit(42)' | cat
  exit "${PIPESTATUS[0]}"
)
ret=$?
echo "The output is $var and the exit code is $ret"

This results in:

The output is hi and the exit code is 42

If you need to extract multiple exit statuses, you'll have to write them to a file or the end of the stream, and then read them back or extract them afterwards.

Upvotes: 2

Gilles Quénot
Gilles Quénot

Reputation: 185053

Like this:

var="$(python SomeScript)" >/dev/null
echo "SomeScript exit code: $?"

Upvotes: 0

Related Questions