Bash Scripting Fundamentals
Learn to write powerful automation scripts with bash.
Your First Script
Every bash script starts with a shebang line that tells the system which interpreter to use:
Save this as hello.sh, make it executable, and run it:
$ ./hello.sh
Hello, World!
Variables
Conditionals
Common Test Operators
| Operator | Description |
|---|---|
| -f file | File exists and is regular file |
| -d dir | Directory exists |
| -z string | String is empty |
| -n string | String is not empty |
| $a -eq $b | Numbers are equal |
| $a -gt $b | a is greater than b |
Loops
Functions
Quoting (the #1 source of bugs)
Bash splits words on spaces and expands globs (*) unless you quote variables.
If you remember one rule: quote your variables.
Exit Codes and Error Handling
In Linux, “success” is exit code 0 and “failure” is anything non-zero.
You can check the last exit code with $?.
Arguments and Flags (getopts)
Scripts become useful when you can pass inputs. Use positional parameters ($1, $2, …)
and getopts for flags.
A Safer Script Template
For production scripts, use a safer default mode and add a cleanup trap.
✅ Practice (20 minutes)
- Write a script that takes
-f(file) and prints the number of lines viawc -l. - Break it by passing a filename with spaces, then fix it using proper quoting.
- Add
set -euo pipefailand intentionally trigger an error to see how it fails fast.
💡 Best Practice
For production scripts, prefer set -euo pipefail (fail fast, catch undefined vars, and detect pipeline failures) and always quote variables. This prevents cascading and hard-to-debug errors.