Chapter 58: Bash Functions
Bash Functions
This is one of the most beautiful and powerful parts of Bash scripting. Once you learn functions, your scripts stop being long messy lists of commands and start looking like clean, organized, reusable building blocks — just like how good programmers write code in any language.
Think of a function like a small reusable recipe card:
- You write the recipe once (the function definition)
- You give it a name
- Later, whenever you need that recipe, you just say the name → the whole recipe runs automatically
So instead of repeating the same 10–15 lines of backup code in five different places, you write it once as a function called backup_folder, and then call it five times with different folder names.
What is a Bash Function? (Super Simple Definition)
A Bash function is:
- A named block of code
- That you can call (run) as many times as you want
- Can take input (arguments)
- Can return/output something
- Lives inside your script (or in ~/.bashrc for global use)
Two Main Ways to Define a Function
Way 1: Most common & modern (recommended)
|
0 1 2 3 4 5 6 7 8 9 |
<span class="line">function_name() {</span> <span class="line"> # commands go here</span> <span class="line"> echo "This is inside the function"</span> <span class="line">}</span> |
Way 2: Older style (still works everywhere)
|
0 1 2 3 4 5 6 7 8 |
<span class="line">function function_name {</span> <span class="line"> # commands</span> <span class="line">}</span> |
Both are fine — most people use Way 1 now (with () after name).
Step-by-Step – Your First Function (Type This Right Now!)
Create a file:
|
0 1 2 3 4 5 6 |
<span class="line">nano my_functions.sh</span> |
Paste this:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<span class="line">#!/bin/bash</span> <span class="line"># ==============================================</span> <span class="line"># Simple greeting function</span> <span class="line"># ==============================================</span> <span class="line">greet() {</span> <span class="line"> echo "======================================="</span> <span class="line"> echo " Namaste! Welcome to Bash Functions "</span> <span class="line"> echo " Today's date: $(date '+%A, %d %B %Y') "</span> <span class="line"> echo "======================================="</span> <span class="line">}</span> <span class="line"># Call the function</span> <span class="line">greet</span> <span class="line">echo "I can call it again..."</span> <span class="line">greet</span> <span class="line">echo "And again!"</span> <span class="line">greet</span> |
Save → make executable → run:
|
0 1 2 3 4 5 6 7 |
<span class="line">chmod +x my_functions.sh</span> <span class="line">./my_functions.sh</span> |
You’ll see the greeting message three times — same code, run three times with one line each time: greet
That’s the magic!
2. Functions with Arguments (Input Parameters)
Functions become really useful when they accept arguments (like $1, $2 in scripts).
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<span class="line"># Function that takes a name as argument</span> <span class="line">say_hello() {</span> <span class="line"> local person="$1" # $1 = first argument</span> <span class="line"> local city="${2:-Hyderabad}" # $2 or default value</span> <span class="line"> echo "Hello $person ji!"</span> <span class="line"> echo "How's the weather in $city today? ☀️"</span> <span class="line">}</span> <span class="line"># Call it different ways</span> <span class="line">say_hello "Rahul"</span> <span class="line">say_hello "Priya" "Delhi"</span> <span class="line">say_hello "Boss" "Mumbai"</span> |
Run it — output:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
<span class="line">Hello Rahul ji!</span> <span class="line">How's the weather in Hyderabad today? ☀️</span> <span class="line">Hello Priya ji!</span> <span class="line">How's the weather in Delhi today? ☀️</span> <span class="line">Hello Boss ji!</span> <span class="line">How's the weather in Mumbai today? ☀️</span> |
local keyword → makes variable only exist inside the function (very good habit — prevents name clashes)
3. Function with Return Value (Output)
Bash functions don’t really “return” values like other languages — instead they:
- Print output (most common)
- Set exit status with return (0 = success, 1–255 = error)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<span class="line">check_disk_space() {</span> <span class="line"> local threshold=80</span> <span class="line"> local usage</span> <span class="line"> usage=$(df -h / | tail -1 | awk '{print $5}' | tr -d '%')</span> <span class="line"> if (( usage >= threshold )); then</span> <span class="line"> echo "Warning: Disk usage is $usage% — almost full!"</span> <span class="line"> return 1 # failure</span> <span class="line"> else</span> <span class="line"> echo "Disk usage is $usage% — looks good!"</span> <span class="line"> return 0 # success</span> <span class="line"> fi</span> <span class="line">}</span> <span class="line"># Call it and check result</span> <span class="line">check_disk_space</span> <span class="line">if [ $? -eq 0 ]; then</span> <span class="line"> echo "All good — no action needed"</span> <span class="line">else</span> <span class="line"> echo "Take action: clean up disk!"</span> <span class="line">fi</span> |
$? after function call = the return value (or last command’s exit status)
4. Real-Life Useful Function Examples
Backup function (reusable)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<span class="line">backup_folder() {</span> <span class="line"> local source="$1"</span> <span class="line"> local backup_dir="${2:-~/backups}"</span> <span class="line"> local date_stamp=$(date +%Y-%m-%d)</span> <span class="line"> local backup_file="${backup_dir}/${source##*/}_$date_stamp.tar.gz"</span> <span class="line"> if [[ ! -d "$source" ]]; then</span> <span class="line"> echo "Error: $source is not a directory!"</span> <span class="line"> return 1</span> <span class="line"> fi</span> <span class="line"> echo "Backing up $source → $backup_file"</span> <span class="line"> tar -czf "$backup_file" -C "$(dirname "$source")" "$(basename "$source")"</span> <span class="line"> if [[ $? -eq 0 ]]; then</span> <span class="line"> echo "Backup successful! 🎯"</span> <span class="line"> else</span> <span class="line"> echo "Backup failed 😢"</span> <span class="line"> return 1</span> <span class="line"> fi</span> <span class="line">}</span> <span class="line"># Use it multiple times</span> <span class="line">backup_folder ~/Documents</span> <span class="line">backup_folder ~/Photos ~/archive</span> <span class="line">backup_folder ~/Downloads/projects</span> |
Color message function
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<span class="line">print_status() {</span> <span class="line"> local message="$1"</span> <span class="line"> local type="${2:-info}"</span> <span class="line"> case "$type" in</span> <span class="line"> success) color="\e[32m" ;; # green</span> <span class="line"> error) color="\e[31m" ;; # red</span> <span class="line"> warning) color="\e[33m" ;; # yellow</span> <span class="line"> *) color="\e[34m" ;; # blue (info)</span> <span class="line"> esac</span> <span class="line"> echo -e "{color}${message}\e[0m"</span> <span class="line">}</span> <span class="line">print_status "Backup completed" success</span> <span class="line">print_status "Disk almost full!" warning</span> <span class="line">print_status "Critical error" error</span> |
Summary Table – Bash Functions Cheat Sheet
Got it, boss? Functions are how your script becomes clean, organized, reusable, and professional — write once, call many times, pass arguments, get results.
Any part confusing? Want next:
- “Teacher, explain how to return values properly (echo vs return)”
- “Functions with arrays as arguments”
- “Recursive functions (function calls itself)”
- “Put functions in separate file & source them”
- “Debug functions with set -x”
Just say — teacher is ready in Hyderabad! Start writing small functions in every script — even 3–4 lines — soon your code will look beautiful! 🐧🛠️🔧 😄
