Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026
The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.
Just like in other programming languages, you can create reusable pieces of code in shell scripts by using functions.
Defining Functions
Define a function with:
function name {
# commands
}
Or the alternative syntax:
name() {
# commands
}
Calling Functions
Call a function by its name:
function greet {
echo "Hello!"
}
greet # outputs: Hello!
Function Parameters
Pass parameters to functions just like script arguments. Access them with $1, $2, etc.:
function greet {
echo "Hello, $1!"
}
greet "Flavio" # outputs: Hello, Flavio!
Practical Example
Here’s a real-world example that processes multiple book folders:
#!/bin/sh
books=( "c-handbook" "css-handbook" "js-handbook" )
generate_book() {
npx honkit pdf ./ ../books/$(basename $PWD).pdf
npx honkit epub ./ ../books/$(basename $PWD).epub
npx honkit mobi ./ ../books/$(basename $PWD).mobi
}
for book in "${books[@]}"
do
echo "Processing $book"
cd $book
generate_book
cd ..
done
The function generate_book is called for each book in the array, avoiding code duplication.
Return Values
Functions can return a status code (0 for success, non-zero for failure):
function check_file {
if [ -f "$1" ]; then
return 0
else
return 1
fi
}
if check_file "myfile.txt"; then
echo "File exists"
else
echo "File not found"
fi
Capturing Output
Use command substitution to capture function output:
function get_date {
date +%Y-%m-%d
}
today=$(get_date)
echo "Today is $today"
Local Variables
Use local to create variables that only exist within the function:
function example {
local my_var="I'm local"
echo $my_var
}
example
echo $my_var # empty - variable doesn't exist here