Search code examples
bashfunctionreturn

Trying to understand bash function return values


I have looked at the bash function return values and it seems I still don't understand how that works. I setup 3 function each supposedly returning a RET_VAL return value. I assume func_1 returns either a 1 or 0 based on the if statement I assume func_2 return either a 1 or a 0 based on the if statement I assume func_3 should either print a 1 or a 0 based on the return value of func_2

func_1() {
  RET_VAL=0
  if [ -d /tmp/dir ]; then
    echo "Dir exists" 
    RET_VAL=0
  else
    echo "Dir doesn't exist"
    RET_VAL=1
  fi
  return ${RET_VAL}
}

func_2() {
  RET_VAL=0
  if func_1; then
    if [ -f /tmp/file_1]; then
      echo "File exists"
    else
      echo "File doesn't exist"
      RET_VAL=1
    fi
  else
    RET_VAL=1
  fi
  return ${RET_VAL}
}

func_3() {
  if func_2; then
    echo "Dir and File do exist"
  else
    echo "Dir and file do not exist"
  fi
}

Are my assumptions correct or is each function returning what it executed last, like the echo statement? If so, how could I assure that the functions return a 1 or a 0 value?

Cheers, Roland


Solution

  • func_3 will not print the return value of func_2. The if statement will use the exit status of func_2 to determine which branch to take. Every command has an exit status, so in the absence of an explicit return command, the exit status of the last command to execute will be the exit status of a function. In the case of func_3, the exit status will be the exit status of whichever echo command executes (which is virtually always 0, absent any I/O errors).