Linux and Bash course menu
Bash Functions: Arguments, local and Return Values
Organise Bash scripts with functions: define and call them, pass arguments, use local variables, return values with echo and exit codes, and share code with source.
On this page
Functions let you name a block of commands and reuse it.
Define and call#
greet() {
echo "Hello!"
}
greet
greetHello!
Hello!A function must be defined before it is called.
Arguments#
Inside a function, $1, $2 and $# refer to the function's own arguments, and you call it like a command, with no brackets:
greet() {
echo "Hello, $1. You are from $2."
}
greet "Asha" "Hyderabad"Hello, Asha. You are from Hyderabad.Local variables#
Variables are global by default, even inside a function. Use local to keep them there:
total=100
change() {
local total=5
echo "Inside: $total"
}
change
echo "Outside: $total"Inside: 5
Outside: 100Always use local for variables inside functions.
Returning values#
return sets only an exit code from 0 to 255, used for success or failure. To give back data, echo it, and capture the output with $(...):
add() {
echo $(( $1 + $2 ))
}
sum=$(add 7 5)
echo "Sum is $sum"Sum is 12Use return to report success or failure, so that the function works in an if:
is_even() {
(( $1 % 2 == 0 ))
}
for n in 3 4; do
if is_even "$n"; then
echo "$n is even"
else
echo "$n is odd"
fi
done3 is odd
4 is evenThe last command's status becomes the function's return value.
check_file() {
if [[ ! -f "$1" ]]; then
echo "Missing: $1" >&2
return 1
fi
return 0
}
check_file /etc/hostname && echo "Found"
check_file /nothing || echo "Status was $?"Found
Missing: /nothing
Status was 1>&2 sends a message to stderr, which keeps error text out of captured output.
All arguments#
"$@" means all the arguments, each kept as a separate word:
show_all() {
echo "Count: $#"
for item in "$@"; do
echo "- $item"
done
}
show_all one "two words" threeCount: 3
- one
- two words
- threeShare functions between scripts#
Put common functions in a file, and load it with source:
cat > lib.sh <<'EOF'
log() {
echo "[$1] $2"
}
EOF
cat > app.sh <<'EOF'
#!/bin/bash
source ./lib.sh
log INFO "Started"
log ERROR "Disk is full"
EOF
bash app.sh[INFO] Started
[ERROR] Disk is fullStructure of a script#
A good script has settings, then functions, then a main:
cat > tidy.sh <<'EOF'
#!/bin/bash
LIMIT=2
report() {
echo "Keeping the newest $LIMIT"
}
main() {
report
echo "Done"
}
main "$@"
EOF
bash tidy.shKeeping the newest 2
DoneCommon mistakes#
Practice#
Practice exercise
Write a function max that prints the larger of two numbers, and use it to print Max: 9 for 4 and 9.
Show solution
max() {
if (( $1 > $2 )); then
echo "$1"
else
echo "$2"
fi
}
echo "Max: $(max 4 9)"Max: 9Key takeaway#
Next: Arguments and Exit Codes.
Finished this lesson?