Skip to main content
Automating routine system maintenance on CentOS (or similar Linux distributions) saves time and reduces human error. In this guide, you’ll learn how to:
  • 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

  1. Understanding the Bash Shell
  2. Creating Your First Script
  3. Automating Backups
  4. Using Exit Status in Conditions
  5. Real-World Example: Anacron
  6. Quick Reference: Shell Constructs
  7. 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.
Bash supports redirection, pipelines, variables, loops, functions, and more—the same features you use interactively are available in scripts.

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

Create archive-dnf.sh:
You can inspect the archive with:

Keeping Two Generations of Backups

To avoid overwriting a good backup, rename the old archive before creating a new one.
  1. Save this as archive-dnf-2.sh:
  2. 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 -q runs 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


Further Resources

Make sure to explore bash built-ins (help) and system scripts under /etc/cron.* for more real-world patterns and advanced techniques.

Watch Video