Functions with Return in Shell

Level 5204 keystrokes

A Bash function passes data back in two ways: by printing it, which the caller captures with $(...), or by its exit status, set with return. calculate_sum prints 15; validate_input only sets a status and is defined but not called here.

Shell code

# Sums all of its arguments and prints the result
1calculate_sum() {
# local keeps result inside the function
2 local result=0
# "$@" is every argument, each kept as one word
3 for num in "$@"; do
# Add num to result arithmetically
4 ((result += num))
5 done
# "Return" the value by printing it
6 echo $result
7}
# Reports through its exit status only (not called in this example)
8validate_input() {
# Status 0 (true) if $1 is all digits, otherwise 1 (false)
9 [[ $1 =~ ^[0-9]+$ ]] && return 0 || return 1
10}
# $(...) captures the function's output: 15
11sum=$(calculate_sum 1 2 3 4 5)
# Print the captured sum
12echo "Sum: $sum"

Output

Sum: 15
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Shell code and how often they appear.

  • $× 6
  • (× 5
  • )× 5
  • "× 4
  • =× 4
  • _× 3
  • [× 3
  • ]× 3
  • {× 2
  • }× 2

More Shell examples at level 5

← Shell typing practice