Suppose I have a C program named Foo.c which is printing few things and returning a value named rc which I am executing in my shell program as follows :
foobar=$(Foo | tail -1)
Now, the variable foobar has the last printed value of the program Foo. But without disturbing this, I want to get the return code rc of the 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 -l
tail: cannot open ‘sat’ for reading: No such file or directory
0
$ 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With