- Write and run simple Bash scripts
- Archive directories reliably
- Manage multiple backup generations
- Use exit statuses in conditions
- Examine a real-world example (Anacron)
Table of Contents
- Understanding the Bash Shell
- Creating Your First Script
- Automating Backups
- Using Exit Status in Conditions
- Real-World Example: Anacron
- Quick Reference: Shell Constructs
- Further Resources
Understanding the Bash Shell
When you log in, you land at a shell prompt managed by bash, the Bourne Again SHell. It interprets commands you type or reads and executes commands from a file (a script) in sequence.Creating Your First Script
Follow these steps to build and run a basic maintenance script.1. Create the Script File
2. Add Script Contents
The first line (
#!/bin/bash) is the shebang, telling the system which interpreter to use.- Lines beginning with
#are comments. >>appends output rather than overwriting.
3. Make the Script Executable
4. Run and Verify
Automating Backups
Backup scripts are ideal for automating directory archiving. Below are two approaches: a simple archive and one that retains the previous generation.Archiving a Directory
Createarchive-dnf.sh:
Keeping Two Generations of Backups
To avoid overwriting a good backup, rename the old archive before creating a new one.-
Save this as
archive-dnf-2.sh: -
Make it executable and run:
Moving or deleting files in
/tmp can remove critical data if misused. Always verify paths and filenames before executing backup scripts.Using Exit Status in Conditions
Every command returns an exit status:0 (success) or nonzero (failure). You can leverage this in if statements:
grep -qruns quietly (-q) and sets exit status accordingly.- Save as
check-grub-timeout.sh, make it executable, then:
Real-World Example: Anacron
Inspect/etc/cron.hourly/0anacron to see conditionals, loops, and file checks in action:
Quick Reference: Shell Constructs
| Construct | Use Case | Example | ||
|---|---|---|---|---|
| shebang | Select interpreter | #!/bin/bash | ||
| if … then | Conditional execution | if grep -q 'foo' file; then echo yes; fi | ||
| for … do | Iterate over lists | for file in *.log; do gzip "$file"; done | ||
>> | Append redirection | date >> /tmp/script.log | ||
test -f | Check file existence | if test -f /path/to/file; then … | ||
| exit status | Check command success/fail | `command && echo success | echo failure` |
Further Resources
Make sure to explore bash built-ins (help) and system scripts under /etc/cron.* for more real-world patterns and advanced techniques.