Bash Scripting Cheat Sheet
This Bash cheat sheet gives you quick examples for common shell scripting syntax, loops, variables, conditions and functions.
Quick Bash scripting reference for writing useful Linux scripts: variables, arguments, if statements, test operators, loops, functions, redirection, exit codes and practical admin snippets.
Script basics
Shebang
#!/usr/bin/env bashMake executable
chmod +x script.shRun script
./script.shRun with bash
bash script.shVariables and quoting
Create variable
NAME="server01"
echo "$NAME"Command substitution
TODAY="$(date +%F)"
HOST="$(hostname)"Quote variables
rm "$FILE"Quoting prevents word splitting and glob surprises.
Read input
read -r -p "Domain: " DOMAINArguments
First argument
echo "$1"Number of arguments
echo "$#"All arguments
for arg in "$@"; do
echo "$arg"
doneUsage check
if [ $# -lt 1 ]; then
echo "Usage: $0 file"
exit 1
fiIf statements
Basic if
if [ -f "$FILE" ]; then
echo "File exists"
fiIf else
if systemctl is-active --quiet nginx; then
echo "Running"
else
echo "Stopped"
fielif
if [ "$USE" -ge 90 ]; then
echo "Critical"
elif [ "$USE" -ge 80 ]; then
echo "Warning"
else
echo "OK"
fiCommon test operators
File tests
[ -f file ] # regular file
[ -d dir ] # directory
[ -e path ] # exists
[ -x file ] # executableString tests
[ -z "$VAR" ] # empty
[ -n "$VAR" ] # not empty
[ "$A" = "$B" ] # equal
[ "$A" != "$B" ] # not equalNumber tests
[ "$A" -eq "$B" ] # equal
[ "$A" -ne "$B" ] # not equal
[ "$A" -gt "$B" ] # greater than
[ "$A" -lt "$B" ] # less thanLoops
For loop
for file in *.log; do
echo "$file"
doneArray loop
SERVICES=("nginx" "mysql" "sshd")
for svc in "${SERVICES[@]}"; do
systemctl status "$svc"
doneRead file line by line
while IFS= read -r line; do
echo "$line"
done < domains.txtFunctions
Simple function
log_msg() {
echo "[$(date +%F_%T)] $*"
}
log_msg "Backup started"Function with argument
check_service() {
systemctl is-active --quiet "$1"
}Exit codes
Check previous command
echo "$?"Exit success
exit 0Exit failure
exit 1Run if previous succeeds
mkdir backup && echo "created"Redirection
Overwrite file
echo "hello" > file.txtAppend to file
echo "hello" >> file.txtRedirect stderr
command 2> errors.logRedirect both
command > output.log 2>&1Useful admin snippets
Check disk usage
USE="$(df / | awk 'NR==2 {gsub(/%/,"",$5); print $5}')"
if [ "$USE" -ge 90 ]; then
echo "Disk critical: ${USE}%"
fiCheck service
if systemctl is-active --quiet nginx; then
echo "nginx OK"
else
echo "nginx failed"
fiFind large files
find /var -xdev -type f -size +500M -exec ls -lh {} \; 2>/dev/nullLog with timestamp
echo "[$(date -Is)] Backup complete" >> /var/log/my-script.logCheck scripts before running them
Bash syntax check
bash -n script.shChecks syntax without running the script.
ShellCheck
shellcheck script.shFinds common Bash mistakes such as missing quotes.
Trace script execution
bash -x script.shShows commands as they run. Useful for debugging.
Safer script mode
set -euo pipefailUseful, but learn how it behaves before adding it everywhere.
Download example scripts
Common errors and fixes
Permission denied
chmod +x script.sh
./script.shBad interpreter
head -n 1 script.sh
dos2unix script.shSyntax check
bash -n script.shDebug line by line
bash -x script.shCommon mistakes
- Forgetting the shebang at the top of the script.
- Forgetting
chmod +xbefore running with./script.sh. - Writing
NAME = valueinstead ofNAME="value". - Not quoting variables, for example using
$FILEinstead of"$FILE". - Using destructive commands before testing what the script will do.
Useful Bash script patterns
Argument check
if [ "$#" -ne 1 ]; then
echo "Usage: $0 FILE"
exit 1
fiSafe read prompt
read -r -p "Continue? Type yes: " answer
[ "$answer" = "yes" ] || exit 0Function pattern
log() {
printf '[%s] %s\n' "$(date +%F_%T)" "$*"
}Loop through files
for file in ./*.log; do
[ -e "$file" ] || continue
echo "$file"
doneFrequently Asked Questions
What should every Bash script start with?
Most Bash scripts should start with a shebang such as #!/usr/bin/env bash.
Why should variables be quoted?
Quoting variables helps avoid word splitting and problems with spaces or empty values.
How do I check script arguments?
Use $# for the number of arguments and $1, $2 and so on for positional arguments.
When should I use functions in Bash?
Use functions when a task is repeated or has a clear single purpose.