Get the return code of a C program in my shell program
You can use "set -o pipefail" option.
[root@myserver Test]# set -o pipefail[root@myserver Test]# ./a.out | tail -l[root@myserver Test]# echo $?100
Here my program a.out returns 100.
Or another options is to use pipestatus environment variable. You can read about it here.http://www.linuxnix.com/2011/03/pipestatus-internal-variable.html
If you are using bash
shell, you can use PIPESTATUS
array variable to get the status of the pipe
process.
$ tail sat | wc -ltail: cannot open ‘sat’ for reading: No such file or directory0$ echo "${PIPESTATUS[0]} ${PIPESTATUS[1]}"1 0$
From man bash
:
PIPESTATUS
An array variable containing a list of exit status values from the processes in the most-recently-executed foreground pipeline (which may contain only a single command).
This assigns the last line of the output of Foo
to foobar
and Foo's exit code is assigned to code
:
{ read -r foobar; read code; } < <( (Foo; echo $? ) | tail -2)
The <(...)
construct is called process substitution. In the code above, the read
commands receive their stdin from the process substitution. Because of the tail -2
, the process substitution produces a total of two lines. The first line is the last line produced by Foo
and it is assigned to foobar
. The second is assigned to code
.
The space between the first and second <
is essential.
Example
After creating a function Foo, the above can be tested:
$ Foo() { echo "Testing"; false; }$ { read -r foobar; read code; } < <( (echo "Testing"; false; echo $? ) | tail -2)$ echo "foobar=$foobar code=$code"foobar=Testing code=1
And:
$ Foo() { echo "2nd Test"; true; }$ { read -r foobar; read code; } < <( (Foo; echo $? ) | tail -2)$ echo "foobar=$foobar code=$code"foobar=2nd Test code=0