basil
basil

Reputation: 720

Function return values within BASH if statements

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?

Upvotes: 3

Views: 8792

Answers (1)

janos
janos

Reputation: 124824

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.

Upvotes: 11

Related Questions