Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the return code of a C program in my shell program

Tags:

c

bash

shell

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.

like image 689
molecule Avatar asked Sep 29 '15 10:09

molecule


2 Answers

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

like image 94
Pratik Shinde Avatar answered Oct 10 '22 07:10

Pratik Shinde


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).

like image 30
sat Avatar answered Oct 10 '22 07:10

sat