0

Let's say I have a C program that evaluates to either a zero or non zero integer; basically a program that evaluates to a boolean value.

I wish to write a shell script that can find out whether the C program evaluates to zero or not. I am currently trying to assign the return value of the C program to a variable in a shell script but seem to be unable to do so. I currently have;

#!/bin/sh
variable=/path/to/executable input1

I know that assigning values in shell script requires us not to have spaces, but I do not know another way around this, since running this seems to evaluate to an error since the shell interprets input1 as a command, not an input. Is there a way I can do this?

I am also unsure as to how to check the return value of the C program. Should I just use an if statement and check if the C program evaluates to a value equal to zero or not?

2
  • BTW: the fact that the program is a c program doesn't mean that you need to tag the question as a c question. Commented Feb 5, 2016 at 15:47
  • Aah, I apologize. I don't go here often. Your advice is noted however. Commented Feb 5, 2016 at 15:51

2 Answers 2

4

This is very basic

#!/bin/sh
variable=`/path/to/executable input1`

or

#!/bin/sh
variable=$(/path/to/executable input1)

and to get the return code from the program use

echo $?
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, it is that simple. Apologies for my noob-ness. Thank you though.
1

You can assign with backticks or $(...) as shown in iharob's answer.

Another way is to interpret a zero return value as success and evaluate that directly (see manual):

if /path/to/executable input1; then
    echo "The return value was 0"
else
    echo "The return value was not 0"
fi

Testing with a little dummy program that exits with 0 if fed "yes" and exits with 1 else:

#!/bin/bash

var="$1"

if [[ $var == yes ]]; then
    exit 0
else
    exit 1
fi

Testing:

$ if ./executable yes; then echo "Returns 0"; else echo "Doesn't return 0"; fi
Returns 0
$ if ./executable no; then echo "Returns 0"; else echo "Doesn't return 0"; fi
Doesn't return 0

If not using Bash: if [ "$var" = "yes" ]; then

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.