IT PATH
My Path

Bash Scripting and Automation

Write safe, readable shell scripts with variables, conditionals, loops, and error handling for real administrative tasks.

Certification
CompTIA Linux+
Recommended study time
6h 35m
Status
Not started

Recommended study time

About 6h 35m in total, measured from the material on this page. At your session length of 45 minutes that is 9 sittings.

  • Read the lesson23 min

    About 2,937 words at a careful technical reading pace.

  • Second pass with notes14 min

    Re-read the harder parts and write your own notes.

  • Recall from memory12 min

    2 written recall questions.

  • Practice decision12 min

    One applied decision with feedback.

  • Teach it back20 min

    Write the topic in your own words.

  • Real-world scenario15 min

    Read the situation and justify your decision in writing.

  • Hands-on practice3h 20m

    Labs, commands and configuration until you can do it unaided.

  • Spaced review1h 40m

    4 short review sessions spread over the following weeks.

Learning objectives

  • Write scripts using variables, conditionals, loops, and functions.
  • Handle errors and exit codes so failures are visible rather than silent.
  • Automate a repetitive administrative task safely with logging and dry-run support.

Start here

About 8 minutes of reading, in 10 short parts.

A shell script is just a saved list of commands, but the difference between a toy script and a production-grade one is whether it fails loudly, checks its assumptions, and can be run twice without causing damage. Automation only pays off if you can trust it while you are asleep.

Where you meet it: A nightly backup job has been silently failing for months, and nobody noticed because the script never checked whether it actually succeeded.

The lesson, part by part

Open one part at a time. Each part stands on its own, so you can stop and come back.

Writing a script is like writing a recipe for someone who will follow it exactly, with no common sense of their own, at three in the morning, with nobody watching. If a step in the recipe is ambiguous — 'add the usual amount of salt' — a human cook improvises, but a script does whatever the ambiguous instruction technically means, which is often not what you wanted. Good scripts spell out every assumption: check the salt is actually in the cupboard before starting, and stop and shout if it is not.

This is also why scripts need to report back. A cook who silently burns dinner and says nothing is worse than one who burns it and tells you immediately. A script that fails without printing an error message or without a way for anyone to notice the failure is functionally the same as no automation at all, because it gives you false confidence that a task happened when it did not.

Key ideas

If you remember nothing else from this topic, remember these.

  • A shell script is just a sequence of commands a human would type, saved to a file and given execute permission, plus control structures for logic and repetition.
  • The shebang line at the top of a script tells the kernel which interpreter to use, and omitting it or getting it wrong causes silent misbehavior rather than an obvious error.
  • Exit codes, not printed text, are how scripts communicate success or failure to each other, with zero meaning success and any nonzero value meaning some kind of failure.
  • Variables are unquoted at your own risk: word splitting and globbing can turn a single filename with a space into two separate arguments if it is not quoted.
  • set -e, set -u, and pipefail turn a script from one that silently continues after an error into one that stops immediately, which is essential for anything run unattended.
  • Automation is valuable specifically because it is repeatable and auditable; a script that only works when its author babysits it is not really automation.

Building a safe automated log cleanup script

A worked example, step by step.

A server's disk keeps filling up because old application logs are never removed, and the fix needs to run unattended every night.

  1. 01Draft the scriptA file cleanup.sh is created starting with #!/bin/bash so the kernel knows to invoke bash to run it.
  2. 02Add safety flagsset -euo pipefail is placed near the top so the script exits immediately on any unhandled error, unset variable, or failed pipeline stage.
  3. 03Write the core logicfind /var/log/app -name '*.log' -mtime +14 -print -delete removes log files older than 14 days and prints each one as it goes.
  4. 04Quote variables properlyA LOG_DIR variable is introduced and every reference to it is written as "$LOG_DIR" to avoid word splitting if the path ever contains a space.
  5. 05Make it executablechmod +x cleanup.sh, then a manual test run confirms it deletes the expected files and nothing else.
  6. 06Check the exit codeecho $? after running the script shows 0, confirming success; a nonzero value would signal a problem to anything calling it.
  7. 07Schedule itA systemd timer unit is created to run the script nightly at 2 AM instead of relying on a raw cron entry.
  8. 08OutcomeDisk usage stabilizes because stale logs are cleared automatically every night, and any failure would halt the script rather than continue and mask the problem.

Outcome: The script runs unattended, fails loudly instead of silently, and is scheduled through systemd for built-in logging.

Bash scripting reference

Worth keeping at hand while you work.

#!/bin/bash
Shebang line telling the kernel which interpreter should run the script.
chmod +x script.sh
Makes a script file executable so it can be run directly.
$?
Holds the exit status of the most recently run command; 0 means success.
set -e
Exits the script immediately if any command returns a nonzero status.
set -u
Treats use of an unset variable as an error instead of substituting an empty string.
set -o pipefail
Makes a pipeline's exit status reflect the first failing command, not just the last one.
"$var"
Quoting a variable prevents word splitting and glob expansion of its contents.
if / then / elif / else / fi
Conditional structure for branching logic in a script.
for / while loops
Repeat a block of commands over a list of items or while a condition holds.
$(command)
Command substitution, capturing a command's output as a string.
cron entry syntax
Minute hour day month weekday command, defining a recurring schedule.
trap 'cleanup' EXIT
Runs a cleanup function automatically when the script exits, even on error.

Common misunderstandings

What most beginners get wrong here.

  • A script that prints no errors ran successfully.

    Success should be confirmed with the exit code $?, since some failures do not produce visible output at all.

  • Variables never need quotes if they are simple strings.

    Any variable that might contain a space or glob character can be word-split or expanded unexpectedly without quotes, so quoting is a habit, not a special case.

  • Forgetting the shebang line just means you have to type bash script.sh instead.

    It also means double-clicking or direct execution can invoke the wrong interpreter entirely, producing confusing syntax errors.

  • set -e makes a script completely safe from unhandled failures.

    It only affects unhandled nonzero exits; conditionals and command substitutions can still mask failures unless pipefail and careful error checks are also used.

  • Cron and systemd timers require the same permission setup as manually run scripts.

    Scheduled jobs often run without the interactive user's environment variables and PATH, so scripts should use absolute paths and not assume a login shell context.

Exam traps

How the question writers try to catch you out.

  • A question describing a script that behaves differently when run by cron versus manually is testing knowledge of environment differences, not script logic.
  • Exit code questions expect you to know 0 is success and any other value is a defined or undefined failure, not that nonzero always means the same thing.
  • Quoting questions often present a filename with a space to test whether you recognize word splitting as the root cause of an unexpected error.
  • A missing shebang line is commonly tested as a cause of a script running with the wrong interpreter rather than simply failing to run.
  • Loop and conditional syntax questions expect exact keywords such as fi and done to close blocks, not just correct logic.

Check yourself

Answer in your head first, then reveal. This is not scored.

  • What does set -u do to a script that references an unset variable?

  • Why should file paths in a scheduled script be absolute rather than relative?

  • What is the risk of leaving a variable unquoted in a command?

  • How do you check whether the previous command in a script succeeded?

  • What does set -o pipefail change about a pipeline's exit status?

Quick reference

A condensed summary of the lesson above, for revision.

What It Is

Bash scripts execute commands sequentially with shell features: variables and quoting, test conditions, if and case, for and while loops, functions, exit codes, and redirection. Robust scripts use set -euo pipefail, validate inputs, quote variables, log actions, and support a dry-run mode before making changes.

Why It Matters

Manual repetition is where mistakes live. Automation converts knowledge into a reviewable artefact, but only if it fails loudly and is idempotent enough to rerun after partial failure.

How It Works

  • The shell expands variables and globs, then executes each command and records its exit status.
  • Conditionals and loops branch on exit codes and test expressions.
  • Scheduled runs through cron or systemd timers execute the script without a terminal, so output must be redirected or logged.

Where You See It

  • Backup jobs, log rotation, deployment tasks, health checks, bulk user changes, and cloud instance bootstrap.

Key Terms

Exit code
Numeric status where zero means success.
set -e
Abort the script on an unhandled command failure.
Idempotent
Safe to run repeatedly with the same end state.
Quoting
Protecting variables from word splitting and globbing.
Cron/timer
Scheduled execution mechanism for recurring jobs.

Examples

  • Unquoted "$file" breaks the moment a filename contains a space.
  • A backup script that checks free space and verifies the archive is far safer than one that assumes success.

Common Problems

  • Unquoted variables
  • Silent failures
  • Assumed working directory
  • Missing environment in cron
  • Non-idempotent operations

How It Fails

  • A missing PATH or environment variable under cron makes a working script fail only when scheduled.
  • An unquoted rm target can delete far more than intended.
  • A partially completed run leaves inconsistent state that a rerun makes worse.

How to Troubleshoot

  1. Run with bash -x to trace expansion and execution.
  2. Reproduce with the same environment the scheduler uses.
  3. Check exit codes explicitly instead of assuming completion.

Practical Knowledge

  • Log start, parameters, actions, and result to a known location.
  • Test destructive scripts with a dry-run mode and a restricted target first.

Exam Coverage

  • Shell scripting constructs
  • Exit codes and error handling
  • Scheduling and automation practices

Interview Questions

  • Why does a script work interactively but fail under cron?
  • How do you make a maintenance script safe to rerun?

Watch and read

Verified official and reputable sources for this topic. Links open in a new tab.

Video training

  • Professor Messer video channel — general CompTIA training (no dedicated CompTIA Linux+ course)

    Professor Messer

    Video
    Free
    Watch
  • Linux Foundation video channel

    The Linux Foundation

    Video
    Free
    Watch

Lesson notes and bookmark

Notes and bookmarks for this lesson, saved with everything else you have marked.

No notes on this item yet.

Learning progress

0% across six evidence areas. Reading alone does not change progress.

Understanding0%
Recall0%
Application0%
Practical ability0%
Troubleshooting0%
Retention0%

Prerequisites

Next steps

  1. 01Rewrite a manual task you do weekly as a logged script with a dry-run flag.
  2. 02Add set -euo pipefail to an existing script and fix what it exposes.