Bash scripting fundamentals
Write robust bash scripts with arguments, conditionals, loops and functions.
By Invicly Tech, , in Linux Administration (RHCSA-style). About 11 minutes to read.
In short
Bash scripts turn command sequences into repeatable tools. A robust script starts with a shebang and strict mode, checks its arguments, quotes every variable, uses functions for structure and returns meaningful exit codes. The RHCSA expects simple scripts with loops, conditionals and arguments.
Explained simply
A bash script is a text file full of the same commands you type at the prompt, plus a little logic: if this, do that; for every file, do something. Once a task works as a script, anyone can run it the same way, every time.
The first line, the shebang, tells Linux which program reads the file, such as #!/usr/bin/env bash. Make the file executable with chmod +x and run it with ./script.sh. Every command returns a number when it ends, called the exit status: 0 means success and anything else means failure.
Scripts get input through arguments. In ./backup.sh /srv 7, $1 is /srv and $2 is 7. Variables hold text, and you should almost always put double quotes around them, as in "$file", so names with spaces do not break into pieces.
Scripts fail in quiet ways unless you ask bash to be strict. set -euo pipefail makes the script stop at the first error instead of carrying on and doing damage. Small functions with clear names make long scripts easy to read and test.
Press Play on a diagram to walk through it one step at a time.
- 1Shebang
#!/usr/bin/env bash
- 2Strict mode
set -euo pipefail stops on errors.
- 3Validate input
Check $# and print usage on misuse.
- 4Functions
Small named steps with local variables.
- 5Main logic
Loops and conditionals on quoted variables.
- 6Exit code
0 for success, non-zero for failure.
- Arguments
- $0 script name
- $1 $2 ... positional
- $# count
- "$@" all, kept separate
- Status
- $? last exit status
- $$ this script's PID
- $! last background PID
- Expansion tricks
- ${v:-def} default
- ${v:?msg} fail if unset
- ${f%.log} strip suffix
- ${p##*/} file name only
In depth
What set -euo pipefail really does, and where it does not
-e exits when a command fails. -u treats an unset variable as an error, so a typo like $fiel stops the script instead of becoming empty text. -o pipefail makes a pipeline fail if any part fails, not just the last command.
But -e has blind spots. It ignores failures inside an if or while condition, in any command before && or ||, and in a function called from such a place. local out=$(cmd) also hides the failure, because local itself succeeds; write local out, then out=$(cmd) on the next line. Treat strict mode as a safety net, not a replacement for checking important commands yourself.
- ${VAR:-default} gives a default and keeps -u happy
- cmd || true lets a command fail on purpose
- bash -n script.sh checks syntax; bash -x script.sh traces each line
Quoting and word splitting
When bash expands an unquoted variable, it splits the result on spaces, tabs and newlines and then expands wildcards. So if file='my report.txt', rm $file tries to remove my and report.txt. rm "$file" removes the one real file. The same goes for $(command): quote it.
"$@" expands to all arguments, each kept as one separate word, which is what you want when passing arguments on. $* joins them into one string. Inside [[ ]] bash does not split words, which is one reason to prefer [[ ]] over the older [ ]. Single quotes keep everything literal, so '$HOME' prints $HOME, while double quotes still expand variables.
- 1Brace expansion
file{1,2} becomes file1 file2
- 2Variables and $( )
$file and $(date) are replaced
- 3Word splitting
Unquoted results split on spaces
- 4Wildcards
Unquoted *.log matches file names
- 5Quote removal, then run
Quotes vanish, the command starts
Tests, case and arithmetic
[[ ]] tests things. Files: -f regular file, -d directory, -e exists, -r readable, -s not empty. Strings: == and != (the right side can be a pattern, such as [[ $f == *.log ]]), -z empty, -n not empty, and =~ for regular expressions. Numbers inside [[ ]] use -eq, -ne, -lt, -le, -gt and -ge.
For maths, (( )) is clearer: (( count > 5 )) tests, and total=$(( a + b )) calculates. Bash only does whole numbers. case is the clean way to handle many choices, such as start, stop and status in one script. Each branch ends with ;; and *) catches everything else.
- [[ -f $cfg ]] || { echo "missing $cfg" >&2; exit 1; }
- (( $# >= 1 )) || usage
- case $1 in start) ... ;; stop) ... ;; *) usage ;; esac
Exit codes, traps and temp files
exit 0 means success. Use small numbers for your own errors and document them. Some numbers are reserved by the shell: 126 means found but not executable, 127 means command not found, and 128 plus N means killed by signal N, so 130 is Ctrl+C. Functions return a status with return, from 0 to 255; they hand back data by printing it.
trap runs code when the script exits or gets a signal. The pattern tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT cleans up temp files even when the script fails halfway. mktemp creates unique names, which avoids clashes and attacks through predictable paths in /tmp.
Options with getopts and safe loops
For flags like -v or -d DAYS, use the built-in getopts. while getopts 'vd:' opt loops over the options; a colon after a letter means it takes a value, found in $OPTARG. After the loop, shift $((OPTIND - 1)) leaves only the normal arguments.
For loops, use globs for files: for f in /var/log/*.log; do ... done. If nothing matches, the pattern stays as literal text, so test with [[ -e $f ]] || continue or turn on shopt -s nullglob. For lines of text, use while IFS= read -r line; do ... done < file. IFS= keeps leading spaces, and -r keeps backslashes. Never loop over $(ls).
Learn it in 5 short steps
About 1h each. Track them with a timer in your plan.
- 1Start with shebang and set -euo pipefail~1h
- 2Handle arguments and exit codes~1h
- 3Use if, test and case~1h
- 4Loop over files and command output~1h
- 5Write functions with local variables~1h
Key points
- Quote variables, as in "$file", so spaces do not split them.
- $1, $2 are arguments, $# is their count and $? is the last exit status.
- [[ -f file ]] tests for a file and [[ $a -gt 5 ]] compares numbers.
- Loop over files with for f in /path/*; loop over lines with while read -r line.
Key terms
Tap a card to flip it. 0/5 known
Examples
#!/usr/bin/env bash
set -euo pipefail
usage() { echo "usage: $0 DIR DAYS" >&2; exit 1; }
[[ $# -eq 2 ]] || usage
dir=$1; days=$2
[[ -d $dir ]] || { echo "no such dir: $dir" >&2; exit 2; }
count=0
while IFS= read -r -d '' f; do
gzip -- "$f"; count=$((count + 1))
done < <(find "$dir" -name "*.log" -mtime +"$days" -print0)
echo "compressed $count files in $dir"Compress logs older than N days, safely handling odd file names.
A service helper with case and getopts
You want one command, svc, that checks, restarts or tails logs of any service, with an optional -n for the number of log lines. Step 1: parse -n with getopts and set a default. Step 2: shift the options away so $1 is the action and $2 the service. Step 3: validate with a usage function. Step 4: use case to pick the action. Each branch returns the status of systemctl, so callers can test it.
#!/usr/bin/env bash
set -euo pipefail
usage() { echo "usage: ${0##*/} [-n LINES] status|restart|logs SERVICE" >&2; exit 2; }
lines=20
while getopts 'n:' opt; do
case $opt in n) lines=$OPTARG ;; *) usage ;; esac
done
shift $((OPTIND - 1))
(( $# == 2 )) || usage
action=$1; svc=$2
case $action in
status) systemctl status --no-pager "$svc" ;;
restart) sudo systemctl restart "$svc" && echo "restarted $svc" ;;
logs) journalctl -u "$svc" -n "$lines" --no-pager ;;
*) usage ;;
esacSafe work in a temp folder
A script downloads a tarball, checks it and unpacks it into /opt/app. If any step fails, nothing half-done should be left behind. Step 1: create a private temp folder with mktemp -d. Step 2: set a trap to delete it on any exit. Step 3: download and verify the checksum; with set -e a mismatch stops the script, and the trap still cleans up. Step 4: only after all checks pass, move the result into place.
#!/usr/bin/env bash
set -euo pipefail
url=${1:?usage: $0 URL SHA256}
sum=${2:?usage: $0 URL SHA256}
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
curl -fsSL -o "$tmp/app.tgz" "$url"
echo "$sum $tmp/app.tgz" | sha256sum -c -
mkdir "$tmp/new" && tar -xzf "$tmp/app.tgz" -C "$tmp/new"
sudo rm -rf /opt/app.old
[[ -d /opt/app ]] && sudo mv /opt/app /opt/app.old
sudo mv "$tmp/new" /opt/app
echo "installed to /opt/app"Quick reference
- Start scripts with #!/usr/bin/env bash and set -euo pipefail
- Quote everything: "$var", "$(cmd)", "$@"
- [[ -f $f ]] file, [[ -z $s ]] empty, (( n > 5 )) numbers
- ${var:-default} fallback, ${var:?message} required, ${f%.txt} strip suffix
- while IFS= read -r line; do ...; done < file reads lines safely
- tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT cleans up on any exit
- Exit 127 = command not found, 126 = not executable, 130 = Ctrl+C
- bash -n checks syntax; bash -x traces execution
Common mistakes
- Unquoted variables that break on spaces or empty values.
- Parsing ls output instead of using globs or find -print0.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a script that takes a user name as its only argument and prints whether that user exists. Exit with 0 if yes and 1 if not.
- Exercise 2medium
Write a script that renames every .jpeg file in a folder to .jpg, works with spaces in names, and does nothing if there are no matches.
- Exercise 3hard
Write a function retry N CMD... that runs a command up to N times with a 2-second pause, returning 0 on the first success and the last exit code on failure.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use #!/bin/bash or #!/usr/bin/env bash?
- Both work on Linux servers, where bash is in /bin or /usr/bin. env finds bash in PATH, which helps on systems where it lives elsewhere, such as macOS with a newer bash from Homebrew.
- What is the difference between [ ] and [[ ]]?
- [ is a normal command, so unquoted variables inside it split and can break the test. [[ is bash syntax: no word splitting, and it supports patterns and =~. Prefer [[ ]] in bash scripts.
- When should I stop writing bash and use Python?
- When you need data structures, JSON, error handling across many steps, or the script grows past a couple of hundred lines. Bash is best for gluing commands together.
- Why does my script work with bash script.sh but not ./script.sh?
- The file is probably not executable (chmod +x), has Windows line endings (fix with sed -i 's/\r$//'), or the shebang points to a missing interpreter.