Shell Scripting: Shell Script Functions

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

Lessons in this unit:

0: Introduction
1: Introduction to Shells
2: Bash Basics
3: Writing Shell Scripts
4: Variables and Environment Variables
5: Loops and Arrays
6: ▶︎ Shell Script Functions
7: Creating Aliases
8: Tips and Tricks
9: The Fish Shell
10: Persist aliases and other configuration in Fish Shell
11: How to add a path to Fish Shell
12: Fish Shell, how to avoid recording commands to history
13: Fish Shell, how to remove the welcome message
14: How to replace all filenames with space with underscore using a shell script
15: How to update all npm packages in multiple projects that sit in subfolders