Bash scripting Bash Scripting Cheat Sheet banner

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 bash

Make executable

chmod +x script.sh

Run script

./script.sh

Run with bash

bash script.sh

Variables 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: " DOMAIN

Arguments

First argument

echo "$1"

Number of arguments

echo "$#"

All arguments

for arg in "$@"; do
  echo "$arg"
done

Usage check

if [ $# -lt 1 ]; then
  echo "Usage: $0 file"
  exit 1
fi

If statements

Basic if

if [ -f "$FILE" ]; then
  echo "File exists"
fi

If else

if systemctl is-active --quiet nginx; then
  echo "Running"
else
  echo "Stopped"
fi

elif

if [ "$USE" -ge 90 ]; then
  echo "Critical"
elif [ "$USE" -ge 80 ]; then
  echo "Warning"
else
  echo "OK"
fi

Common test operators

File tests

[ -f file ]  # regular file
[ -d dir ]   # directory
[ -e path ]  # exists
[ -x file ]  # executable

String tests

[ -z "$VAR" ]      # empty
[ -n "$VAR" ]      # not empty
[ "$A" = "$B" ]    # equal
[ "$A" != "$B" ]   # not equal

Number tests

[ "$A" -eq "$B" ]  # equal
[ "$A" -ne "$B" ]  # not equal
[ "$A" -gt "$B" ]  # greater than
[ "$A" -lt "$B" ]  # less than

Loops

For loop

for file in *.log; do
  echo "$file"
done

Array loop

SERVICES=("nginx" "mysql" "sshd")
for svc in "${SERVICES[@]}"; do
  systemctl status "$svc"
done

Read file line by line

while IFS= read -r line; do
  echo "$line"
done < domains.txt

Functions

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 0

Exit failure

exit 1

Run if previous succeeds

mkdir backup && echo "created"

Redirection

Overwrite file

echo "hello" > file.txt

Append to file

echo "hello" >> file.txt

Redirect stderr

command 2> errors.log

Redirect both

command > output.log 2>&1

Useful admin snippets

Check disk usage

USE="$(df / | awk 'NR==2 {gsub(/%/,"",$5); print $5}')"
if [ "$USE" -ge 90 ]; then
  echo "Disk critical: ${USE}%"
fi

Check service

if systemctl is-active --quiet nginx; then
  echo "nginx OK"
else
  echo "nginx failed"
fi

Find large files

find /var -xdev -type f -size +500M -exec ls -lh {} \; 2>/dev/null

Log with timestamp

echo "[$(date -Is)] Backup complete" >> /var/log/my-script.log

Check scripts before running them

Bash syntax check

bash -n script.sh

Checks syntax without running the script.

ShellCheck

shellcheck script.sh

Finds common Bash mistakes such as missing quotes.

Trace script execution

bash -x script.sh

Shows commands as they run. Useful for debugging.

Safer script mode

set -euo pipefail

Useful, but learn how it behaves before adding it everywhere.

Download example scripts

Common errors and fixes

Permission denied

chmod +x script.sh
./script.sh

Bad interpreter

head -n 1 script.sh
dos2unix script.sh

Syntax check

bash -n script.sh

Debug line by line

bash -x script.sh

Common mistakes

  • Forgetting the shebang at the top of the script.
  • Forgetting chmod +x before running with ./script.sh.
  • Writing NAME = value instead of NAME="value".
  • Not quoting variables, for example using $FILE instead of "$FILE".
  • Using destructive commands before testing what the script will do.
Script patterns

Useful Bash script patterns

Argument check

if [ "$#" -ne 1 ]; then
  echo "Usage: $0 FILE"
  exit 1
fi

Safe read prompt

read -r -p "Continue? Type yes: " answer
[ "$answer" = "yes" ] || exit 0

Function pattern

log() {
  printf '[%s] %s\n' "$(date +%F_%T)" "$*"
}

Loop through files

for file in ./*.log; do
  [ -e "$file" ] || continue
  echo "$file"
done
FAQ

Frequently 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.