How to act on an error code and collect stdout at the same time?

local‘s exit code overrides the one from the command substitution. To work around this, always split apart local declarations from assignments if the assignments could fail:

local URI
URI=`python3 example.py $DB`
RESULT=$?

By the way, you don’t need to save the exit code in a variable if you check it in the if statement. Also, it’s best to avoid uppercase variable names as they could clash with built-in names. Finally, I recommend using $(...) in place of backticks; it is easier to nest substitutions.

local db=$1

local uri
if uri=$(python3 example.py "$db"); then
    echo "$uri"
    echo success
else
    echo failed
fu

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top