Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function return values within BASH if statements

Tags:

linux

bash

shell

sh

I have looked at various ways on here handle function return values within BASH if-then statements, but none seem to work. Here is what I've got

 function is_cloned()
 {
      if [ -d $DIR_NAME ]
      then
           return $SUCCESS
      fi
      return $FAILURE
 }

It will work if I call it on its own and check the return value like:

 is_cloned
 retval=$?
 if [ $retval -eq $FAILURE ] 
 then
      ...
 fi

How can I use the function call within the if statement? Or is there no way at all to take advantage of the return values?

like image 634
basil Avatar asked Nov 21 '25 09:11

basil


1 Answers

if statements in Bash can use the exit code of functions directly. So you can write like this:

if is_cloned
then
    echo success
fi

If you want to check for failure, as in your posted code, you could use the ! operator:

if ! is_cloned
then
    echo failure
fi

By the way, your is_cloned function too can rely more on exit codes, you can write like this:

is_cloned() {
    [ -d "$DIR_NAME" ]
}

This works, because the exit code of a function is the exit code of the last executed command, and the exit code of [ ... ] is 0 if successful, non-zero otherwise (= failure).

Also remember to double-quote variable names used as command arguments, as I did DIR_NAME here.

like image 131
janos Avatar answered Nov 22 '25 22:11

janos