Before you start writing a complex shell script, you should plan what the script will do and how it will do it.
This planning is a critical part of designing an effective script in any programming language. Without thinking through your script before you start writing it, you are likely to waste a lot of time and have an inefficient script when you have finished.
By the end of this module you will be able to:
- Define a clear script objective
- Diagram the flow of control through a script
- Decide which types of tests will work best in your script
- Test commands before using them in a script
- Include error-checking in your script
- Create a script that works in multiple shells
Defining a clear objective for your Unix shell script is essential to ensure your script is purposeful, efficient, and maintainable. Here's a structured approach to help you define one:
- Identify the Problem or Task
- What manual task am I trying to automate?
- Is this a repetitive, error-prone, or time-consuming activity?
- Example: "I need to back up all
.log
files from /var/log
to /backup/logs/
every day."
- Clarify the Expected Input and Output
- What input the script expects (e.g., file names, directories, arguments)?
- What output or result it should produce (e.g., report, archive, notification)?
- Example: Input:
/var/log/*.log
, Output: Archived file logs_backup_YYYYMMDD.tar.gz
in /backup/logs/
- Define the Environment
- Which shell? (
bash
, sh
, zsh
, etc.)
- Which OS or Linux distribution?
- Are you using cron, systemd, or manual execution?
- Set a Single, Measurable Goal
- Specific
- Measurable
- Achievable
- Relevant
- Time-bound (if applicable)
✅ *Objective Example:*
"This script automates the daily backup of log files from `/var/log` into a compressed archive stored in `/backup/logs/`."
✍️ Template for Script Objective (Add as a Comment at Top)
#!/bin/bash
# Script Name: backup_logs.sh
# Objective: Automatically archive all .log files from /var/log into /backup/logs/ on a daily basis.
# Author: Your Name
# Date: YYYY-MM-DD