Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I execute a curl [url] command in a Linux shell script. I want to get this command's exit code and its output at the same time without using a temporary file.

Is there any method to do that?

like image 569
herozgx Avatar asked Sep 05 '25 03:09

herozgx


2 Answers

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/bash

function 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"
}

test1
test2

Output:

# ./test.sh
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 0ms
0: 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/bash

function 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"
}

test1
test2

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 0ms
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 0ms
like image 29
rtillery Avatar answered Sep 07 '25 20:09

rtillery



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!