A Bash Cheat Sheet#

A quick reference for the most important Bash commands, syntax, and idioms.

File and Directory Operations#

Command

Purpose

ls [-la]

List files (a=all, l=long format)

pwd

Print working directory

cd DIR

Change directory

mkdir [-p] DIR

Create directory (p=parents)

rm [-rf] FILE

Remove file or directory

cp [-r] SRC DEST

Copy file or directory

mv SRC DEST

Move or rename

touch FILE

Create empty file or update timestamp

find PATH -name PATTERN

Find files matching pattern

locate FILE

Find file by name (uses database)

Viewing File Content#

Command

Purpose

cat FILE

Display entire file

less FILE

View file with paging

head [-n N] FILE

Show first N lines (default 10)

tail [-n N] FILE

Show last N lines

wc [-l] FILE

Count lines, words, characters

grep PATTERN FILE

Search for pattern in file

grep -i PATTERN FILE

Case-insensitive search

grep -r PATTERN DIR

Recursive search in directory

Text Processing and Transformation#

Command

Purpose

sed 's/OLD/NEW/' FILE

Replace first occurrence per line

sed 's/OLD/NEW/g' FILE

Replace all occurrences

awk '{print $1}' FILE

Print first field of each line

awk 'NR > 1' FILE

Skip header row

sort FILE

Sort lines alphabetically

sort -n FILE

Sort numerically

uniq FILE

Remove consecutive duplicate lines

cut -d: -f1 FILE

Cut by delimiter, extract field

tr 'a-z' 'A-Z'

Translate characters (uppercase)

Permissions and Ownership#

Command

Purpose

chmod 755 FILE

Set permissions (rwxr-xr-x)

chmod +x FILE

Add execute permission

chmod -w FILE

Remove write permission

chown USER FILE

Change file owner

chown USER:GROUP FILE

Change owner and group

chgrp GROUP FILE

Change group ownership

umask 022

Set default permissions mask

Process and System Information#

Command

Purpose

ps

Show current processes

ps aux

Show all processes with details

top

Interactive process monitor

kill PID

Terminate process by ID

kill -9 PID

Force kill process

bg

Run job in background

fg

Bring job to foreground

jobs

List background jobs

&

Run command in background (append to command)

uname -a

System information

df -h

Disk space usage (human readable)

du -sh DIR

Directory size

free -h

Memory usage

whoami

Current user

id

User and group IDs

Bash Variables and Expansion#

Syntax

Meaning

$VAR

Variable value

${VAR}

Variable value (explicit boundaries)

${VAR:-DEFAULT}

Use DEFAULT if VAR is unset

${VAR:=DEFAULT}

Set and use DEFAULT if unset

${VAR:+VALUE}

Use VALUE if VAR is set

${VAR#PATTERN}

Remove shortest prefix match

${VAR##PATTERN}

Remove longest prefix match

${VAR%PATTERN}

Remove shortest suffix match

${VAR%%PATTERN}

Remove longest suffix match

${VAR/OLD/NEW}

Replace first occurrence

${VAR//OLD/NEW}

Replace all occurrences

${!PREFIX*}

Names of variables starting with PREFIX

${#VAR}

Length of variable

$(COMMAND)

Command substitution

`COMMAND`

Command substitution (deprecated)

$((EXPR))

Arithmetic expansion

Conditional Testing#

Test

Meaning

[ -f FILE ]

File exists and is regular file

[ -d DIR ]

Directory exists

[ -e FILE ]

File exists (any type)

[ -z STR ]

String is empty

[ -n STR ]

String is not empty

[ STR1 = STR2 ]

Strings are equal

[ STR1 != STR2 ]

Strings are not equal

[ NUM1 -eq NUM2 ]

Numbers are equal

[ NUM1 -ne NUM2 ]

Numbers are not equal

[ NUM1 -lt NUM2 ]

NUM1 less than NUM2

[ NUM1 -le NUM2 ]

NUM1 less than or equal

[ NUM1 -gt NUM2 ]

NUM1 greater than NUM2

[ NUM1 -ge NUM2 ]

NUM1 greater than or equal

[[ STR =~ REGEX ]]

String matches regex (Bash only)

[ COND1 -a COND2 ]

Logical AND

[ COND1 -o COND2 ]

Logical OR

[ ! COND ]

Logical NOT

Control Flow#

# if-then-else
if CONDITION; then
  COMMANDS
elif CONDITION; then
  COMMANDS
else
  COMMANDS
fi

# case statement
case "$VAR" in
  PATTERN1) COMMANDS ;;
  PATTERN2) COMMANDS ;;
  *) DEFAULT_COMMANDS ;;
esac

# for loop
for VAR in LIST; do
  COMMANDS
done

# while loop
while CONDITION; do
  COMMANDS
done

# until loop
until CONDITION; do
  COMMANDS
done

Functions#

function_name() {
  COMMANDS
  return EXIT_CODE
}

# Call function with arguments
function_name arg1 arg2 arg3

# Inside function, arguments are:
# $1 = arg1, $2 = arg2, $3 = arg3
# $@ = all arguments
# $# = number of arguments
# $0 = script name

Redirection and Pipes#

Operator

Purpose

> FILE

Redirect stdout to file (overwrite)

>> FILE

Redirect stdout to file (append)

< FILE

Redirect stdin from file

2> FILE

Redirect stderr to file

2>&1

Redirect stderr to stdout

| COMMAND

Pipe stdout to command

|& COMMAND

Pipe stdout and stderr to command

&> FILE

Redirect both stdout and stderr

Special Variables#

Variable

Meaning

$0

Script name

$1, $2, …

Positional parameters

$@

All positional parameters (quoted array)

$*

All positional parameters (unquoted)

$#

Number of positional parameters

$?

Exit code of last command

$$

Process ID of current shell

$!

Process ID of last background job

$-

Current shell options

$LINENO

Current line number

$SECONDS

Seconds since shell startup

String Operations#

# Length
${#string}

# Substring from position 0, length 5
${string:0:5}

# Remove prefix
${string#prefix}
${string##prefix}  # longest match

# Remove suffix
${string%suffix}
${string%%suffix}  # longest match

# Replace first/all
${string/find/replace}
${string//find/replace}

# Uppercase/Lowercase (Bash 4+)
${string^^}  # uppercase
${string,,}  # lowercase

Arrays#

# Indexed array
arr=(value1 value2 value3)
arr[0]="new_value"
arr+=("new_element")

# Associative array (requires declare -A)
declare -A map
map[key1]="value1"
map[key2]="value2"

# Access
${arr[0]}      # First element
${arr[@]}      # All elements
${arr[*]}      # All elements as string
${!arr[@]}     # All indices
${#arr[@]}     # Array length

Common Patterns#

Loop through files#

for file in *.txt; do
  echo "Processing $file"
done

Check if file exists#

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

Default value#

filename="${1:-.bashrc}"  # Use .bashrc if $1 not provided

Safe script header#

#!/bin/bash
set -euo pipefail
trap 'echo "Error on line $LINENO"' ERR

Check for required arguments#

if [[ $# -lt 2 ]]; then
  echo "Usage: script.sh ARG1 ARG2"
  exit 1
fi

Error handling#

if ! command; then
  echo "Command failed" >&2
  exit 1
fi

Important Flags#

Common command flags#

  • -v or --verbose - Verbose output

  • -f or --force - Force operation

  • -r or -R - Recursive

  • -n or --dry-run - Show what would be done

  • -h or --help - Show help

  • -V or --version - Show version