MAK MAK - 5 months ago 12
Bash Question

Unix shell script: exit with returning value

I have the following unix shell script, in which i have two integer
variables namely a and b.

If a is greater then or equal to b then shell script should exit with returning 0.

Else it should exit with returning 1.

My try:



Script: ConditionTest.sh

#!/bin/sh

a=10
b=20

if [ $a -ge $b ]
then
exit 0
else
exit 1
fi
....
....
....


Running Script:

$ ./ConditionTest.sh
$


Note: I am not getting any return value after executing the file.

Answer

The shell puts the exit status of the last command in the variable $?. You could simply inspect it:

mycommand
echo $?

... or you could use it to do something else depending on its value:

mycommand && echo "ok" || echo "failed"

or alternatively, and slightly more readable:

if mycommand; then
  # exit with 0
  echo "ok"
else
  # exit with non-zero
  echo "failed"
if