NASutils Knowledge BaseUnofficialPolski

Bash · lesson 13 of 30 · Data, functions and the command lineReturn a code

return sets the code that if and $? read.

Programming on the NAS › Bash in 30 lessons

13-return.sh Download 13-return.sh

#!/usr/app/TurboShell/bin/bash
# return sets the exit code of a function, so if can ask it
is_number() {
  [[ $1 =~ ^-?[0-9]+$ ]]
}

level() {
  local used=$1
  ((used < 80)) && return 0
  ((used < 95)) && return 1
  return 2
}

for used in 75 93 97 many; do
  if ! is_number "$used"; then
    echo "$used: not a number"
    continue
  fi
  level "$used"
  echo "$used: level $?"
done

Terminal

$ bash 13-return.sh
75: level 0
93: level 1
97: level 2
many: not a number

Exercise

Write is_weekend for a day's name.