Bash Scripting Cheat Sheet: Variables, Conditions, Loops and Safe Defaults
· Editorial team · 2 min read
cheatsheetbashshellscriptingdevops
Safe script header
#!/usr/bin/env bash
set -euo pipefail # exit on error, unset var, failed pipe stage
IFS=$'\n\t'Variables and expansion
name="Asha"
echo "Hello, $name"
echo "${name:-default}" # default if unset or empty
echo "${#name}" # length
echo "${name^^}" # uppercase (Bash 4+)
today=$(date +%F) # command substitution
echo $((3 + 4 * 2)) # arithmetic
args=("$@") # array of arguments| Special | Meaning | |---|---| | `$0` `$1`..`$9` | Script name, positional args | | `$@` / `$#` | All args (quote it) / count | | `$?` | Exit status of last command | | `$$` | Current PID |
Conditions
if [[ -f "$file" && -r "$file" ]]; then
echo "readable file"
elif [[ -d "$file" ]]; then
echo "directory"
else
echo "other"
fi| Test | True when | |---|---| | `-f` / `-d` / `-e` | Regular file / directory / exists | | `-z s` / `-n s` | String empty / not empty | | `a == b` | Strings equal | | `-eq -ne -lt -gt -le -ge` | Numeric comparisons |
Loops
for f in *.txt; do echo "$f"; done
for i in {1..5}; do echo "$i"; done
while IFS= read -r line; do echo "$line"; done < input.txtFunctions and cleanup
log() { printf '[%s] %s\n' "$(date +%T)" "$*" >&2; }
tmp=$(mktemp)
trap 'rm -f "$tmp"' EXIT # runs on exit, even after failureRedirection and pipes
| Syntax | Effect | |---|---| | `cmd > f` / `cmd >> f` | Overwrite / append stdout | | `cmd 2> err` | Redirect stderr | | `cmd > f 2>&1` | stdout and stderr to the same file | | `cmd1 \| cmd2` | Pipe stdout to the next command | | `cmd <<< "text"` | Here-string as stdin |
Common mistakes
Stop spending an hour tailoring each resume — get a tailored resume and cover letter for this job in seconds.
Tailor my resumeEditorial team
Writes practical guides for Indian job seekers. Part of the HireStraight editorial team. Subscribe via RSS.