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 result1calculate_sum() { # local keeps result inside the function2 local result=0 # "$@" is every argument, each kept as one word3 for num in "$@"; do # Add num to result arithmetically4 ((result += num))5 done # "Return" the value by printing it6 echo $result7}# 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 110}# $(...) captures the function's output: 1511sum=$(calculate_sum 1 2 3 4 5)# Print the captured sum12echo "Sum: $sum"Output
Sum: 15
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