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.

Create a free account to save this page, take notes and track your progress. Sign in

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.

Functions, local variables and return status
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 N sets 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?

  1. return "text"
  2. Print it and capture the output with $(...)
  3. Set $RESULT globally
  4. exit "text"
Show answer

Answer: Print it and capture the output with $(...)

Was this page helpful?