Menu
CoddyTech

Returning Values

Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 14 of 39.

A function gives back data by printing it. $(command), called command substitution, runs a command and puts what it printed in its place, so you can store a function's output in a variable.

square() {
  echo $(( $1 * $1 ))
}
area=$(square 6)
echo "Area: $area"

This prints Area: 36. For a yes or no answer, use return N: it ends the function with exit code N, 0 for success and 1 to 255 for failure. if runs its branch when the code is 0.

is_weekend() {
  if [[ $1 == Sat || $1 == Sun ]]; then
    return 0
  fi
  return 1
}
if is_weekend Sun; then echo "Closed"; else echo "Open"; fi

This prints Closed, and is_weekend Tue in the same line would print Open. return carries a number, never text, so data always goes out through echo.

challenge icon

Challenge

Medium

Write a parcel script with one function that gives back a cost and one that answers yes or no.

  1. Open parcel.sh. Its first argument is a weight in kilos.
  2. Define cost, which prints the cost of a parcel that weighs $1 kilos: 3 per kilo plus 2.
  3. Define is_heavy, which prints nothing and returns 0 when its argument is greater than 20, and 1 otherwise.
  4. Below the functions, store $(cost "$1") in a variable and print Cost: followed by it.
  5. Then, if is_heavy "$1" succeeds, print Heavy parcel.
  6. Save the file.

Try it: run bash parcel.sh 5. It prints:

Cost: 17

Then run bash parcel.sh 25, which is over the limit:

Cost: 77
Heavy parcel

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Bash Scripting

Practice on your own: Terminal playground