A Bash Cheat Sheet#
A quick reference for the most important Bash commands, syntax, and idioms.
File and Directory Operations#
Command |
Purpose |
|---|---|
|
List files (a=all, l=long format) |
|
Print working directory |
|
Change directory |
|
Create directory (p=parents) |
|
Remove file or directory |
|
Copy file or directory |
|
Move or rename |
|
Create empty file or update timestamp |
|
Find files matching pattern |
|
Find file by name (uses database) |
Viewing File Content#
Command |
Purpose |
|---|---|
|
Display entire file |
|
View file with paging |
|
Show first N lines (default 10) |
|
Show last N lines |
|
Count lines, words, characters |
|
Search for pattern in file |
|
Case-insensitive search |
|
Recursive search in directory |
Text Processing and Transformation#
Command |
Purpose |
|---|---|
|
Replace first occurrence per line |
|
Replace all occurrences |
|
Print first field of each line |
|
Skip header row |
|
Sort lines alphabetically |
|
Sort numerically |
|
Remove consecutive duplicate lines |
|
Cut by delimiter, extract field |
|
Translate characters (uppercase) |
Permissions and Ownership#
Command |
Purpose |
|---|---|
|
Set permissions (rwxr-xr-x) |
|
Add execute permission |
|
Remove write permission |
|
Change file owner |
|
Change owner and group |
|
Change group ownership |
|
Set default permissions mask |
Process and System Information#
Command |
Purpose |
|---|---|
|
Show current processes |
|
Show all processes with details |
|
Interactive process monitor |
|
Terminate process by ID |
|
Force kill process |
|
Run job in background |
|
Bring job to foreground |
|
List background jobs |
|
Run command in background (append to command) |
|
System information |
|
Disk space usage (human readable) |
|
Directory size |
|
Memory usage |
|
Current user |
|
User and group IDs |
Bash Variables and Expansion#
Syntax |
Meaning |
|---|---|
|
Variable value |
|
Variable value (explicit boundaries) |
|
Use DEFAULT if VAR is unset |
|
Set and use DEFAULT if unset |
|
Use VALUE if VAR is set |
|
Remove shortest prefix match |
|
Remove longest prefix match |
|
Remove shortest suffix match |
|
Remove longest suffix match |
|
Replace first occurrence |
|
Replace all occurrences |
|
Names of variables starting with PREFIX |
|
Length of variable |
|
Command substitution |
|
Command substitution (deprecated) |
|
Arithmetic expansion |
Conditional Testing#
Test |
Meaning |
|---|---|
|
File exists and is regular file |
|
Directory exists |
|
File exists (any type) |
|
String is empty |
|
String is not empty |
|
Strings are equal |
|
Strings are not equal |
|
Numbers are equal |
|
Numbers are not equal |
|
NUM1 less than NUM2 |
|
NUM1 less than or equal |
|
NUM1 greater than NUM2 |
|
NUM1 greater than or equal |
|
String matches regex (Bash only) |
|
Logical AND |
|
Logical OR |
|
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 |
|---|---|
|
Redirect stdout to file (overwrite) |
|
Redirect stdout to file (append) |
|
Redirect stdin from file |
|
Redirect stderr to file |
|
Redirect stderr to stdout |
|
Pipe stdout to command |
|
Pipe stdout and stderr to command |
|
Redirect both stdout and stderr |
Special Variables#
Variable |
Meaning |
|---|---|
|
Script name |
|
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 |
|
Current line number |
|
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#
-vor--verbose- Verbose output-for--force- Force operation-ror-R- Recursive-nor--dry-run- Show what would be done-hor--help- Show help-Vor--version- Show version