Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

SH
Bash Scripting
0/12 completed
Beginner
Your first scriptVariables and argumentsQuoting and expansionInput, output and redirection
Intermediate
Conditions and testsLoopsFunctionsArrays and string tricks
Advanced
Text processing: grep, sed and awkError handling and debugging
Pro
Cron and schedulingProduction-ready scripts
Tracks / Bash Scripting / Intermediate

Functions

A function is a named group of commands. Functions keep scripts readable ("backup_database" says more than 15 lines of commands), let you reuse code, and make scripts much easier to test and change.

Defining and calling

bash
greet() {
  echo "Hello, $1!"
}

greet Asha
greet "Ravi Kumar"
Output
Hello, Asha!
Hello, Ravi Kumar!
  • Define it with name() { … } before you call it (Bash reads scripts top to bottom).
  • Call it like any command: name, then arguments. No parentheses when calling.
  • Inside, the arguments are $1, $2, $# and "$@", just like a script's.

Local variables

Variables in Bash are global by default, even inside functions. That causes surprising bugs:

bash
count=10
bump() {
  count=99         # oops: changes the global
  local temp=5     # only exists inside the function
  echo "inside: count=$count temp=$temp"
}
bump
echo "outside: count=$count temp=[$temp]"
Output
inside: count=99 temp=5
outside: count=99 temp=[]

💡 Declare every variable inside a function with local. It's the single best habit for bug-free functions.

Returning values

Functions have two ways to send something back:

  1. An exit code with return N (0–255): for success or failure.
  2. Output: anything the function prints, which the caller captures with $( ).
bash
is_even() {
  (( $1 % 2 == 0 ))      # the exit code of the last command is returned
}

square() {
  echo $(( $1 * $1 ))
}

for n in 3 4; do
  if is_even "$n"; then echo "$n is even"; else echo "$n is odd"; fi
done
result=$(square 12)
echo "12 squared is $result"
Output
3 is odd
4 is even
12 squared is 144

return is for status, not data: return 300 wraps around to 44, and you can't return text. Print the data and capture it instead.

Because the output is the return value, functions that return data must send messages to stderr so they don't end up in the result:

bash
get_version() {
  echo "reading version…" >&2
  echo "2.4.1"
}
v=$(get_version)
echo "version is [$v]"
Output
reading version…
version is [2.4.1]

Validating arguments

bash
create_user() {
  local name=$1 role=${2:-viewer}
  if [[ -z $name ]]; then
    echo "create_user: a name is required" >&2
    return 1
  fi
  echo "created $name with role $role"
}

create_user asha admin
create_user ravi
create_user || echo "failed with exit code $?"
Output
created asha with role admin
created ravi with role viewer
create_user: a name is required
failed with exit code 1

Passing arrays and lists

Pass several values with "$@", and loop over them inside:

bash
backup_all() {
  local dest=$1
  shift                # the rest of the arguments are files
  local file
  for file in "$@"; do
    echo "copy '$file' → $dest/"
  done
  echo "$# files queued"
}
files=("notes.txt" "my photo.jpg" "data.csv")
backup_all /mnt/backup "${files[@]}"
Output
copy 'notes.txt' → /mnt/backup/
copy 'my photo.jpg' → /mnt/backup/
copy 'data.csv' → /mnt/backup/
3 files queued

(Arrays are covered properly in the next lesson.)

A script built from functions

Larger scripts follow one pattern: helpers at the top, the work in small functions, and a main function at the bottom that ties them together.

deploy.sh
#!/usr/bin/env bash
set -euo pipefail

log()  { printf '[%s] %s\n' "$(date -u +%H:%M:%S)" "$*" >&2; }
die()  { log "ERROR: $*"; exit 1; }

check_branch() {
  local branch=$1
  [[ $branch == main || $branch == release-* ]] || die "refusing to deploy branch '$branch'"
  log "branch $branch is deployable"
}

build() {
  log "building…"
  mkdir -p dist && echo "<h1>shop</h1>" > dist/index.html
}

upload() {
  local target=$1
  log "uploading $(find dist -type f | wc -l) file(s) to $target"
}

main() {
  local branch=${1:?usage: deploy.sh BRANCH [TARGET]}
  local target=${2:-staging}
  check_branch "$branch"
  build
  upload "$target"
  log "done"
}

main "$@"
bash
bash deploy.sh main production 2>&1 | sed 's/^\[[0-9:]*\]/[time]/'
echo "---"
bash deploy.sh feature-x 2>&1 | sed 's/^\[[0-9:]*\]/[time]/'
Output
[time] branch main is deployable
[time] building…
[time] uploading 1 file(s) to production
[time] done
---
[time] ERROR: refusing to deploy branch 'feature-x'

(The sed replaces the real timestamps with [time] so the output above stays the same each run.)

  • log and die are tiny helpers you'll copy into almost every script.
  • main "$@" at the end passes the script's arguments to main, so the whole script reads top to bottom like a table of contents.
  • set -euo pipefail stops the script on errors. It's explained in Error handling and debugging.

Libraries with source

Put shared functions in a file and load them into any script with source:

lib.sh
# lib.sh: shared helpers
log() { echo "[log] $*"; }
require() { command -v "$1" > /dev/null || { echo "missing: $1" >&2; return 1; }; }
bash
source ./lib.sh
log "lib loaded"
require bash && log "bash is installed"
require kubectl || log "install kubectl first"
Output
[log] lib loaded
[log] bash is installed
missing: kubectl
[log] install kubectl first

command -v name is the reliable way to check whether a program is installed.

Functions in your terminal

Functions in ~/.bashrc become your own commands. A favourite:

bash
mkcd() { mkdir -p -- "$1" && cd -- "$1"; }
mkcd projects/new-app
pwd
Output
/home/you/projects/new-app

An alias can't do this, because aliases can't take arguments in the middle of a command. Functions can.

Practice

  1. Write max A B that prints the larger of two numbers.
  2. Write is_file_older PATH DAYS that returns success if the file was last changed more than DAYS days ago (hint: find "$1" -mtime +"$2").
  3. Restructure one of your earlier scripts into functions with a main.
  4. Write confirm "question" that asks [y/N] and returns 0 only for y or yes. Use it as if confirm "Continue?"; then ….
✎ Check your understanding

1.How do you call a function greet with the argument Asha?

2.A function needs to give back the text "2.4.1". How?

3.Why use local inside functions?

← Loops