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"; fiThis 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
MediumWrite a parcel script with one function that gives back a cost and one that answers yes or no.
- Open
parcel.sh. Its first argument is a weight in kilos. - Define
cost, which prints the cost of a parcel that weighs$1kilos: 3 per kilo plus 2. - Define
is_heavy, which prints nothing and returns 0 when its argument is greater than 20, and 1 otherwise. - Below the functions, store
$(cost "$1")in a variable and printCost:followed by it. - Then, if
is_heavy "$1"succeeds, printHeavy parcel. - Save the file.
Try it: run bash parcel.sh 5. It prints:
Cost: 17Then run bash parcel.sh 25, which is over the limit:
Cost: 77
Heavy parcelTry it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit ConverterPractice on your own: Terminal playground