UFC Insider
UFC Insider

Reputation: 838

What's wrong here? (Comparing an exit code)

I want to compare the exit code of a program to an argument. This is what I'm doing:

CODE=$1
if [[ $(./program) -eq $CODE ]]; then
    echo "same"
else
    echo "different"
fi

Where $1 gets "1". But I'm getting an error. What's wrong here?

Upvotes: 0

Views: 68

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 754020

You're not comparing the exit code; you're comparing the standard output of the program with $CODE.

Maybe:

CODE="$1"
./program
rc=$?
if [[ "$rc" -eq "$CODE" ]]
then echo "same"
else echo "different"
fi

You could just use $? in the condition, but you might want it for reporting and validation:

CODE="$1"
./program
rc=$?
if [[ "$rc" -eq "$CODE" ]]
then echo "same ($rc and $CODE)"
else echo "different (got $rc, wanted $CODE)"
fi

Upvotes: 5

Related Questions