Bash Scripting Tutorial: Write Your First Useful Script
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.
On this page
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:
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 inif,while, or on the left of&&and||don't trigger an exit.set -u: error on undefined variables. Catches typos like$USRENAMEinstead of$USERNAME.set -o pipefail: pipe failures count as errors. Without it,cmd1 | cmd2succeeds whenevercmd2succeeds, even ifcmd1failed.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):
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:
$ 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:
# 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):
$ 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:
$ ./cleanup.sh --days 7 --dir /tmp
That's a real, useful operational script. What each piece does:
- Argument parsing: the
case "$1" in ... esacblock handles--days,--dir,--dry-runand--help.shiftconsumes one or two positional arguments per option. - Validation: the
if [[ ! -d "$DIR" ]]check catches typos in the directory path before anything runs. - The
find ... -print0plusread -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, socountsurvives it. - Cross-platform
stat: GNUstatuses-c %s, BSD and macOSstatuse-f %z. Try the GNU form first; on macOS it fails cleanly and the fallback runs. (The reverse order is a trap: GNUstat -fmeans "file system status" and prints junk intosize.) - 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:
# 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:
$ 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.
What to read next
- Bash one-liners we actually use, for the commands worth keeping in your history
- systemd timers vs cron, for scheduling a script once it works
- Linux troubleshooting guide, for watching what your scripts do once they run
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
Cite this article
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
[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)
More from Linux
Explore more articles in this category
CVE-2026-98432: The CVSS 9.8 Linux TCP Bug Now Has an Exploit. Patched Node Images
A use-after-free in the IPv4 TCP handshake, present since Linux 4.4, now has a working exploit against MPTCP listeners, and every Go 1.24+ server is one by default. Which kernels are fixed and how to roll them through EKS, GKE and AKS.
CERN Left Red Hat for Debian: The CPU Baseline Lesson
CERN is moving accelerator control computers to Debian because RHEL raised its minimum CPU level. Check your own fleet's x86-64-vN support before the next OS upgrade does it for you.
ext4 vs XFS vs Btrfs: Choosing a Filesystem for a Server
The default filesystem your distro picks is not always the right one for your workload. Here is what actually differs and when each one wins.
You might have missed
Evergreen posts worth revisiting.