AnyCompiler

Function Return Values

A function's own return keyword works exactly like a command's exit code — it can only be a number from 0 to 255, and by convention 0 still means success. It cannot send back a string or any other real value the way return does in every typed language on this site.

is_even() {
  if (( $1 % 2 == 0 )); then
    return 0
  else
    return 1
  fi
}
is_even 4
echo "4 is even: $?"
is_even 3
echo "3 is even: $?"
Output
4 is even: 0
3 is even: 1

To actually get a value back out of a function, the idiom is to echo it and capture that output with command substitution, exactly like capturing any other command's output — the function below doesn't use return at all for its result, only for (implicitly) signaling success.

double() {
  echo $(( $1 * 2 ))
}
result=$(double 21)
echo "$result"
Output
42

Next: string manipulation — length, case conversion, and substitution, all through parameter expansion syntax rather than method calls.

Practice exercise

Write a function named square that echoes the square of its one argument, then call it with 6, capture the result with command substitution into a variable, and print that variable.