0
0
Bash Scriptingscripting~3 mins

Why Calling functions in Bash Scripting? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write a command once and use it anytime without repeating yourself?

The Scenario

Imagine you have a long list of commands to run every day, like backing up files, cleaning logs, and sending reports. You write them all out each time in your script without grouping them.

The Problem

Typing the same commands over and over is slow and boring. If you make a mistake, you have to fix it everywhere. It's easy to forget a step or mix up the order, causing errors.

The Solution

Calling functions lets you bundle commands into one named block. You write the commands once, then just call the function whenever you need it. This keeps your script neat and easy to fix.

Before vs After
Before
echo "Start backup"
tar -czf backup.tar.gz /mydata
echo "Backup done"
echo "Start cleanup"
rm -rf /tmp/*
echo "Cleanup done"
After
backup() {
  echo "Start backup"
  tar -czf backup.tar.gz /mydata
  echo "Backup done"
}

cleanup() {
  echo "Start cleanup"
  rm -rf /tmp/*
  echo "Cleanup done"
}

backup
cleanup
What It Enables

You can reuse and organize your commands easily, making scripts faster to write and safer to run.

Real Life Example

System administrators use functions to automate daily tasks like updating software, checking disk space, and restarting services without rewriting code each time.

Key Takeaways

Functions group commands into reusable blocks.

Calling functions reduces repeated code and errors.

Scripts become cleaner and easier to maintain.