avd
avd

Reputation: 14441

Checking return value of a C++ executable through shell script

I am running a shell script on windows with cygwin in which I execute a program multiple times with different arguments each time. Sometimes, the program generates segmentation fault for some input arguments. I want to generate a text file in which the shell script can write for which of the inputs, the program failed. Basically I want to check return value of the program each time it runs. Here I am assuming that when program fails, it returns a different value from that when it succeeds. I am not sure about this. The executable is a C++ program.

Is it possible to do this? Please guide. If possible, please provide a code snippet for shell script.

Also, please tell what all values are returned.

My script is .sh file.

Upvotes: 4

Views: 3450

Answers (4)

Jonathan Leffler
Jonathan Leffler

Reputation: 753725

Assuming no significant spaces in your command line arguments:

cat <<'EOF' |
-V
-h
-:
-a whatnot peezat
!

while read args
do
    if program $args
    then : OK
    else echo "!! FAIL !! ($?) $args" >> logfile
    fi
done

This takes a but more effort (to be polite about it) if you must retain spaces. Well, a bit more effort; you probably use an eval in front of the 'program'.

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254461

You can test the return value using shell's if command:

if program; then
    echo Success
else
    echo Fail
fi

or by using "and" or "or" lists to do extra commands only if yours succeeds or failed:

program && echo Success
program || echo Fail

Note that the test succeeds if the program returns 0 for success, which is slightly counterintuitive if you're used to C/C++ conditions succeeding for non-zero values.

Upvotes: 0

Andrey
Andrey

Reputation: 60065

if it is bat file you can use %ERRORLEVEL%

Upvotes: 0

Didier Trosset
Didier Trosset

Reputation: 37437

The return value of the last program that finished is available in the environment variable $?.

Upvotes: 3

Related Questions