Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix shell script: exit with returning value

Tags:

shell

unix

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.

like image 945
MAK Avatar asked Dec 19 '22 16:12

MAK


2 Answers

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
like image 117
Kusalananda Avatar answered Jan 16 '23 12:01

Kusalananda


Your script looks fine; you did everything right.

#!/bin/sh

a=10
b=20

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

So here's where we run it and check the return value:

$ sh test.sh
$ echo $?
1
$

10 is not greater than or equal to 20.

Another way to test it would be like this:

$ sh test.sh && echo "succeeded" || echo "failed"
failed

As noted in the comments, you should also quote your variables, always:

if [ $a -ge $b ]

Should be:

if [ "$a" -ge "$b" ]
like image 30
Will Avatar answered Jan 16 '23 12:01

Will