(bash)

CIS241

System-Level Programming and Utilities

bash Functions

Erik Fredericks, frederer@gvsu.edu
Fall 2025

Based on material provided by Erin Carrier, Austin Ferguson, and Katherine Bowers

CIS241 | Fredericks | F25 | 24-bash-functions

Declaring and calling functions

function my_function() {
  commands
}

# To call:
my_function 
CIS241 | Fredericks | F25 | 24-bash-functions

Function parameters

Just like normal command line arguments!

function my_function() {
  echo "You passed: $1"
}

# To call:
my_function foo
CIS241 | Fredericks | F25 | 24-bash-functions

A TEST

function repeat() {
  range=$(seq 0 $2)
  for i in $range; do
    echo "$1"
  done
}

repeat "hello" 5
repeat "!!!" 10
repeat $1 $2

What does this do?

CIS241 | Fredericks | F25 | 24-bash-functions

Scope

You have to mark variables as local (and is good practice)

function my_function() {
  local x
  x=5
  echo "Inside function: x = ${x}"
}

x=1
echo "Before function: x = ${x}"
my_function
echo "After function: x = ${x}"
CIS241 | Fredericks | F25 | 24-bash-functions

Return values

Return value in $?

function functionName()  {
  # Do stuff
  return 10
}
functionName
echo $?
CIS241 | Fredericks | F25 | 24-bash-functions

Return values

function functionName()  {
  # Do stuff
  echo "Hi there!"
  return 10
}
val=$( functionName )
echo $val

What happens?

CIS241 | Fredericks | F25 | 24-bash-functions

Trapping signals

Remember the whole kill command? You can handle it!

Common signals:
Ctrl+CSIGINT (2) → Interrupt process
Ctrl+ZSIGSTP (18) → Stop/pause process

kill -9SIGKILL (9) → Cannot be trapped!

# Trap a signal
trap "<command to run>" <signal to trap>
trap "echo THIS IS A TRAP" SIGINT
CIS241 | Fredericks | F25 | 24-bash-functions

Why relevant here?

Make your programs die gracefully!

function endScript {
  # write out important data
}
trap endScript EXIT
CIS241 | Fredericks | F25 | 24-bash-functions

all variables global by default

make an example...