Bash Tutorial · Bash Scripting · Lesson 19 of 30
Bash Functions
Define functions, pass arguments, return values with output and exit codes, and keep variables local.
Defining and calling
Functions take arguments like scripts: $1, $2, ... and $@ for all of them. Use local for variables
so they don't leak into the rest of the script.
greet() {
local name="${1:-friend}"
echo "Hello, $name"
}
greet Ana
greet
is_port_free() {
local port=$1
(( port != 8080 )) # pretend 8080 is in use
}
for p in 8080 8081; do
if is_port_free "$p"; then echo "$p is free"; else echo "$p is in use"; fi
done
slugify() { local s="${1,,}"; echo "${s// /-}"; }
title="Hello World Post"
echo "slug: $(slugify "$title")"
Output
Hello, Ana Hello, friend 8080 is in use 8081 is free slug: hello-world-post
Run this on your computer — see “Get Started” for setup.
Returning values
- Print the result and capture it with
$(...). return Nsets the exit status (0-255): use it for success/failure, not data.
Test yourself
How should a Bash function return a string to its caller?
return "text"Print it and capture the output with $(...)Set $RESULT globallyexit "text"
Show answer
Answer: Print it and capture the output with $(...)