How to get exit code and stdout of a linux command at the same time How to get exit code and stdout of a linux command at the same time shell shell

How to get exit code and stdout of a linux command at the same time


I'm assuming the problem is that you have an intermediary command that's supplanting the exit code of the last command.

To get around this, just store the exit code and stdout in variables:

OUTPUT=$(curl example.org)EXIT_CODE=$?

then you can simply output these either in the same line:

echo "$EXIT_CODE: $OUTPUT"

or call them separately as needed.


(I don't have enough reputation points to comment on user559633's answer.)

Apparently this won't work if you send STDOUT to a local variable:

test.sh:

#!/bin/bashfunction test1 () {    OUTPUT=$( ping -c 1 -W 1 blah.org )    EXIT_CODE=$?    echo "$EXIT_CODE: $OUTPUT"}function test2 () {    local OUTPUT=$( ping -c 1 -W 1 blah.org )    EXIT_CODE=$?    echo "$EXIT_CODE: $OUTPUT"}test1test2

Output:

# ./test.sh1: PING blah.org (205.150.150.140) 56(84) bytes of data.--- blah.org ping statistics ---1 packets transmitted, 0 received, 100% packet loss, time 0ms0: PING blah.org (205.150.150.140) 56(84) bytes of data.--- blah.org ping statistics ---1 packets transmitted, 0 received, 100% packet loss, time 0ms

Note the exitcode from test1 is 1, but for test2, it's 0.

EDIT: It seems that separating the local declaration from the assignment takes care of this:

#!/bin/bashfunction test1 () {    OUTPUT=$( ping -c 1 -W 1 blah.org )    EXIT_CODE=$?    echo "$EXIT_CODE: $OUTPUT"}function test2 () {    local OUTPUT    OUTPUT=$( ping -c 1 -W 1 blah.org )    EXIT_CODE=$?    echo "$EXIT_CODE: $OUTPUT"}test1test2

Output:

1: PING blah.org (205.150.150.140) 56(84) bytes of data.--- blah.org ping statistics ---1 packets transmitted, 0 received, 100% packet loss, time 0ms1: PING blah.org (205.150.150.140) 56(84) bytes of data.--- blah.org ping statistics ---1 packets transmitted, 0 received, 100% packet loss, time 0ms


There's no standard way to get the exit status of a command within a pipe.

However, if you're using (or able to use) Bash as your shell, the PIPESTATUS built-in array variable holds the results of the most recent pipeline executed. (Note that a single command counts as a pipeline here).

Example:

true | false | false | false; echo "${PIPESTATUS[0]}" "${PIPESTATUS[1]}"

Output:

0 1