Skip to main content
Bash Scripting Tutorial: Write Your First Useful Script

Bash Scripting Tutorial: Write Your First Useful Script

KU
· Founder & Chief Editor
• 8 min read•Updated •41 views

Build a real disk-cleanup script step by step. Learn variables, conditionals, loops, error handling, and the safety preamble that prevents foot-guns.

Key takeaways

  • A Bash script is a text file that starts with a shebang line such as #!/usr/bin/env bash, made executable with chmod +x and run as ./script.sh.
  • Add set -euo pipefail so errors stop the script, quote every variable, give destructive scripts a dry-run mode, and lint everything with ShellCheck before running it.

To write your first Bash script, create a file that starts with #!/usr/bin/env bash and set -euo pipefail, add your commands, run chmod +x script.sh, then execute it with ./script.sh. Below we build a disk-cleanup script with argument parsing, a --dry-run mode and error handling, then lint it with ShellCheck. About 25 minutes.

Verified against

GNU Bash 5.3, ShellCheck v0.11.0, against the GNU Bash release archive and ShellCheck's README and releases. Checked October 2026.

You'll need a Linux or macOS terminal with bash (check with bash --version). macOS ships an old Bash 3.2 as /bin/bash; everything here works on it, but brew install bash gets you a current one.

Why bash is worth learning even in 2026

Bash is the common language of operations. Every Linux server has it. Every CI runner has it. Most containers have it, or at least a POSIX sh. For small "glue between commands" tasks, nothing beats it for speed and ubiquity. For anything beyond about 150 lines, reach for Python; the small stuff is bash.

Step 1: The safety preamble

Every non-trivial bash script starts with this:

Bash
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'

What each does:

  • #!/usr/bin/env bash: the shebang line. It says "use bash, find it via PATH," which works on macOS and most Linux distros.
  • set -e: exit when a command fails. Without it, scripts blunder past failures. It has exceptions: commands tested in if, while, or on the left of && and || don't trigger an exit.
  • set -u: error on undefined variables. Catches typos like $USRENAME instead of $USERNAME.
  • set -o pipefail: pipe failures count as errors. Without it, cmd1 | cmd2 succeeds whenever cmd2 succeeds, even if cmd1 failed.
  • IFS=$'\n\t': only split words on newlines and tabs, not spaces, so unquoted filenames with spaces break less often.

These lines prevent a big chunk of the "but it worked on my laptop" bash bugs. Use them.

Step 2: Variables and quoting

Variables are simple: NAME=value (no spaces around =). Reference them with $NAME. Always quote the reference: "$NAME", not $NAME.

Why the quotes matter (with the default IFS):

Bash
NAME="Alice Smith"
echo $NAME       # prints: Alice Smith (works by accident)
ls $NAME         # tries to ls TWO files: Alice and Smith
ls "$NAME"       # tries to ls one file: "Alice Smith"

Always quoting is the safe default. ShellCheck (the linter we use at the end) catches missing quotes.

Try this in your terminal:

Bash
$ NAME="${USER:-stranger}"
$ echo "Hello, $NAME"
Hello, kiril

The ${VAR:-default} syntax means: use $VAR if set, otherwise default. Useful for optional config.

Step 3: Build the cleanup script

Create cleanup.sh:

Bash
#!/usr/bin/env bash
# cleanup.sh: report or delete files older than N days
set -euo pipefail
IFS=$'\n\t'

# Default values
DAYS="${DAYS:-30}"
DIR="${DIR:-/tmp}"
DRY_RUN=0

# Parse args
while [[ $# -gt 0 ]]; do
    case "$1" in
        --days) DAYS="$2"; shift 2 ;;
        --dir) DIR="$2"; shift 2 ;;
        --dry-run) DRY_RUN=1; shift ;;
        --help)
            echo "Usage: $0 [--days N] [--dir PATH] [--dry-run]"
            echo "  Find files older than N days in DIR (default: 30 days, /tmp)"
            exit 0
            ;;
        *) echo "Unknown arg: $1" >&2; exit 1 ;;
    esac
done

if [[ ! -d "$DIR" ]]; then
    echo "Error: $DIR is not a directory" >&2
    exit 1
fi

echo "Scanning $DIR for files older than $DAYS days..."

count=0
total_size=0
while IFS= read -r -d '' file; do
    size=$(stat -c %s "$file" 2>/dev/null || stat -f %z "$file")  # Linux, then macOS
    total_size=$((total_size + size))
    count=$((count + 1))
    if [[ $DRY_RUN -eq 1 ]]; then
        echo "[dry-run] would delete: $file"
    else
        rm -- "$file"
        echo "deleted: $file"
    fi
done < <(find "$DIR" -type f -mtime +"$DAYS" -print0)

echo
echo "Files: $count"
echo "Total size: $((total_size / 1024 / 1024)) MB"
if [[ $DRY_RUN -eq 1 ]]; then
    echo "(dry run: nothing actually deleted)"
fi

Make it executable, then run it in dry-run mode first (always, for any script that deletes things):

Bash
$ chmod +x cleanup.sh
$ ./cleanup.sh --dry-run --days 7 --dir /tmp

You should see a list of files older than 7 days in /tmp that it would delete, with a count and total size at the end. Nothing is deleted. If that looks right, drop --dry-run:

Bash
$ ./cleanup.sh --days 7 --dir /tmp

That's a real, useful operational script. What each piece does:

  • Argument parsing: the case "$1" in ... esac block handles --days, --dir, --dry-run and --help. shift consumes one or two positional arguments per option.
  • Validation: the if [[ ! -d "$DIR" ]] check catches typos in the directory path before anything runs.
  • The find ... -print0 plus read -d '' loop: the standard way to loop safely over files with arbitrary names, including spaces and newlines. Process substitution (< <(...)) keeps the loop in the current shell, so count survives it.
  • Cross-platform stat: GNU stat uses -c %s, BSD and macOS stat use -f %z. Try the GNU form first; on macOS it fails cleanly and the fallback runs. (The reverse order is a trap: GNU stat -f means "file system status" and prints junk into size.)
  • The closing if: ending a script with [[ $DRY_RUN -eq 1 ]] && echo ... looks tidy, but when the test is false the script exits with status 1 and your CI job fails for no visible reason.

Step 4: Functions and trap

Bigger scripts benefit from functions and cleanup hooks:

Bash
#!/usr/bin/env bash
# work.sh: a skeleton with logging and temp-dir cleanup
set -euo pipefail

WORKDIR=$(mktemp -d)
trap 'rm -rf "$WORKDIR"' EXIT

log() {
    echo "[$(date '+%H:%M:%S')] $*" >&2
}

main() {
    log "Working in $WORKDIR"
    # ... do stuff with $WORKDIR ...
    log "Done"
}

main "$@"

trap '<command>' EXIT runs the command when the script exits, whether it succeeded or failed. Ideal for cleaning up temp files. Don't name the variable TMPDIR: mktemp and many other tools read that environment variable, and overwriting it changes where child processes put their temp files.

log() is a tiny convention: write status to stderr (>&2) so it doesn't pollute stdout, which a pipeline might consume. main "$@" at the bottom runs the logic, passing through the original arguments.

Step 5: Lint with ShellCheck

ShellCheck catches a whole category of bash bugs automatically. Install it and run it on your script:

Bash
$ brew install shellcheck          # macOS
$ sudo apt install shellcheck      # Ubuntu/Debian
$ shellcheck cleanup.sh

Fix anything it flags. Each warning has a code like SC2086 (unquoted variable) with an explanation on the ShellCheck wiki. Run it in CI too.

Common mistakes

Forgetting quotes. Probably the most common bash bug. Unquoted variables silently break on filenames with spaces, empty values, or glob characters. Quote everything.

Using [ ... ] instead of [[ ... ]]. The single-bracket form is older and less forgiving. [[ ... ]] supports pattern and regex matching and doesn't word-split. It is bash-only, but you're writing bash.

Skipping the safety preamble. Without set -euo pipefail, scripts continue past failures. Every rm -rf "$UNSET_VAR"/ disaster is a missing set -u.

Parsing complex output with cut and awk. Once a script is parsing JSON or doing nontrivial logic, you've outgrown bash. Move to Python (or at least jq). The migration is faster than the next bug.

Questions people ask

How do I run a bash script?

Make it executable with chmod +x script.sh and run ./script.sh; the shebang line picks the interpreter. Or skip the permission step and run bash script.sh. Typing just script.sh fails unless the file's directory is on your PATH, which is why the ./ prefix matters. Running it with sh script.sh may use a different shell and break bash-only syntax like [[ ]].

What does set -euo pipefail do?

It makes a bash script fail loudly. -e exits when a command returns non-zero, -u treats unset variables as errors, and -o pipefail makes a pipeline fail if any command in it fails, not just the last. Together they stop a script from carrying on after an error. -e is skipped inside if tests and &&/|| lists, so check those explicitly.

Should I use bash or Python for scripts?

Use bash for short glue: running commands in order, moving files, wrapping CLIs, CI steps under roughly 100 to 150 lines. Switch to Python once you parse structured data like JSON, need real error handling, data structures or tests, or the script keeps growing. The tipping point is when you start fighting quoting and string parsing instead of solving the problem.

Bash is a glue skill, and the most useful 50 lines you write this year will probably be bash. Get the safety preamble into muscle memory, quote your variables, lint with ShellCheck, and you avoid the worst classes of bugs.

Sources

Explore topics:Linux
React
Share this post
Cite this article
Plain text

Kiril Urbonas (2026). Bash Scripting Tutorial: Write Your First Useful Script. DevOpsNess. Updated 2026-10-31. https://www.devopsness.com/blog/bash-scripting-tutorial-first-script

Markdown

[Bash Scripting Tutorial: Write Your First Useful Script](https://www.devopsness.com/blog/bash-scripting-tutorial-first-script) (Kiril Urbonas, DevOpsNess, updated 2026-10-31)

KU

Kiril Urbonas

Founder & Chief Editor

586 articles
View all articles by Kiril Urbonas

You might have missed

Evergreen posts worth revisiting.