Returning a boolean from a Bash function Returning a boolean from a Bash function bash bash

Returning a boolean from a Bash function


Use 0 for true and 1 for false.

Sample:

#!/bin/bashisdirectory() {  if [ -d "$1" ]  then    # 0 = true    return 0   else    # 1 = false    return 1  fi}if isdirectory $1; then echo "is directory"; else echo "nopes"; fi

Edit

From @amichair's comment, these are also possible

isdirectory() {  if [ -d "$1" ]  then    true  else    false  fi}isdirectory() {  [ -d "$1" ]}


Why you should care what I say in spite of there being a 250+ upvote answer

It's not that 0 = true and 1 = false. It is: zero means no failure (success) and non-zero means failure (of type N).

While the selected answer is technically "true" please do not put return 1** in your code for false. It will have several unfortunate side effects.

  1. Experienced developers will spot you as an amateur (for the reason below).
  2. Experienced developers don't do this (for all the reasons below).
  3. It is error prone.
    • Even experienced developers can mistake 0 and 1 as false and true respectively (for the reason above).
  4. It requires (or will encourage) extraneous and ridiculous comments.
  5. It's actually less helpful than implicit return statuses.

Learn some bash

The bash manual says (emphasis mine)

return [n]

Cause a shell function to stop executing and return the value n to its caller. If n is not supplied, the return value is the exit status of the last command executed in the function.

Therefore, we don't have to EVER use 0 and 1 to indicate True and False. The fact that they do so is essentially trivial knowledge useful only for debugging code, interview questions, and blowing the minds of newbies.

The bash manual also says

otherwise the function’s return status is the exit status of the last command executed

The bash manual also says

($?) Expands to the exit status of the most recently executed foreground pipeline.

Whoa, wait. Pipeline? Let's turn to the bash manual one more time.

A pipeline is a sequence of one or more commands separated by one of the control operators ‘|’ or ‘|&’.

Yes. They said 1 command is a pipeline. Therefore, all 3 of those quotes are saying the same thing.

  • $? tells you what happened last.
  • It bubbles up.

My answer

So, while @Kambus demonstrated that with such a simple function, no return is needed at all. I think was unrealistically simple compared to the needs of most people who will read this.

Why return?

If a function is going to return its last command's exit status, why use return at all? Because it causes a function to stop executing.

Stop execution under multiple conditions

01  function i_should(){02      uname="$(uname -a)"0304      [[ "$uname" =~ Darwin ]] && return0506      if [[ "$uname" =~ Ubuntu ]]; then07          release="$(lsb_release -a)"08          [[ "$release" =~ LTS ]]09          return10      fi1112      false13  }1415  function do_it(){16      echo "Hello, old friend."17  }1819  if i_should; then20    do_it21  fi

What we have here is...

Line 04 is an explicit[-ish] return true because the RHS of && only gets executed if the LHS was true

Line 09 returns either true or false matching the status of line 08

Line 13 returns false because of line 12

(Yes, this can be golfed down, but the entire example is contrived.)

Another common pattern

# Instead of doing this...some_commandif [[ $? -eq 1 ]]; then    echo "some_command failed"fi# Do this...some_commandstatus=$?if ! $(exit $status); then    echo "some_command failed"fi

Notice how setting a status variable demystifies the meaning of $?. (Of course you know what $? means, but someone less knowledgeable than you will have to Google it some day. Unless your code is doing high frequency trading, show some love, set the variable.) But the real take-away is that "if not exist status" or conversely "if exit status" can be read out loud and explain their meaning. However, that last one may be a bit too ambitious because seeing the word exit might make you think it is exiting the script, when in reality it is exiting the $(...) subshell.


** If you absolutely insist on using return 1 for false, I suggest you at least use return 255 instead. This will cause your future self, or any other developer who must maintain your code to question "why is that 255?" Then they will at least be paying attention and have a better chance of avoiding a mistake.


myfun(){    [ -d "$1" ]}if myfun "path"; then    echo yesfi# ormyfun "path" && echo yes