Returning a boolean from a Bash function

luca picture luca · Mar 25, 2011 · Viewed 219.1k times · Source

I want to write a bash function that check if a file has certain properties and returns true or false. Then I can use it in my scripts in the "if". But what should I return?

function myfun(){ ... return 0; else return 1; fi;}

then I use it like this:

if myfun filename.txt; then ...

of course this doesn't work. How can this be accomplished?

Answer

Erik picture Erik · Mar 25, 2011

Use 0 for true and 1 for false.

Sample:

#!/bin/bash

isdirectory() {
  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" ]
}