What if you could write a command once and use it anytime without repeating yourself?
Why Calling functions in Bash Scripting? - Purpose & Use Cases
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.
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.
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.
echo "Start backup" tar -czf backup.tar.gz /mydata echo "Backup done" echo "Start cleanup" rm -rf /tmp/* echo "Cleanup done"
backup() {
echo "Start backup"
tar -czf backup.tar.gz /mydata
echo "Backup done"
}
cleanup() {
echo "Start cleanup"
rm -rf /tmp/*
echo "Cleanup done"
}
backup
cleanupYou can reuse and organize your commands easily, making scripts faster to write and safer to run.
System administrators use functions to automate daily tasks like updating software, checking disk space, and restarting services without rewriting code each time.
Functions group commands into reusable blocks.
Calling functions reduces repeated code and errors.
Scripts become cleaner and easier to maintain.