Bash System Commands Cheat Sheet
1. Test Operators ([ ] and [[ ]])
File Tests
● -f file - True if file exists and is regular file
● -d file - True if file exists and is directory
● -e file - True if file exists (any type)
● -r file - True if file is readable
● -w file - True if file is writable
● -x file - True if file is executable
● -s file - True if file exists and has size > 0
● -L file - True if file is symbolic link
● -O file - True if file is owned by current user
● -G file - True if file is owned by current group
● -N file - True if file was modified since last read
● file1 -nt file2 - True if file1 newer than file2
● file1 -ot file2 - True if file1 older than file2
String Tests
● -z string - True if string length is zero
● -n string - True if string length is non-zero
● string1 = string2 - True if strings are equal
● string1 != string2 - True if strings are not equal
● string1 < string2 - True if string1 sorts before string2
● string1 > string2 - True if string1 sorts after string2
Numeric Tests
● num1 -eq num2 - Equal
● num1 -ne num2 - Not equal
● num1 -lt num2 - Less than
● num1 -le num2 - Less than or equal
● num1 -gt num2 - Greater than
● num1 -ge num2 - Greater than or equal
Examples:
[ -f "file.txt" ] && echo "File exists"
[ -d "/home" ] && echo "Directory exists"
[ $a -eq $b ] && echo "Numbers are equal"
[ -z "$var" ] && echo "Variable is empty"
2. Special Variables
Process Variables
● $$ - PID of current shell
● $! - PID of last background process
● $? - Exit status of last command (0 = success)
● $0 - Name of script/shell
● $1, $2, $3... - Command line arguments
● $# - Number of arguments
● $* - All arguments as single string
● $@ - All arguments as separate items
System Variables
● $HOME - Home directory
● $PATH - Command search path
● $PWD - Current working directory
● $USER - Current username
● $SHELL - Current shell
● $PS1 - Primary prompt
● $IFS - Internal Field Separator
● $RANDOM - Random number (0-32767)
3. Command Operators
Redirection
● > - Redirect stdout to file (overwrite)
● >> - Redirect stdout to file (append)
● < - Redirect stdin from file
● 2> - Redirect stderr to file
● 2>&1 - Redirect stderr to stdout
● &> - Redirect both stdout and stderr
● | - Pipe output to next command
● tee - Write to both file and stdout
Control Operators
● && - AND (run next command only if previous succeeds)
● || - OR (run next command only if previous fails)
● ; - Command separator (always run next)
● & - Run command in background
● ! - Logical NOT
● () - Run commands in subshell
● {} - Run commands in current shell
Examples:
command1 && command2 # Run command2 only if command1 succeeds
command1 || command2 # Run command2 only if command1 fails
command1 ; command2 # Run both commands regardless
command & # Run command in background
4. Arithmetic and Expansions
Arithmetic Expansion
● $(( expression )) - Arithmetic evaluation
● $[ expression ] - Older arithmetic syntax
● let "var = expression" - Arithmetic assignment
Parameter Expansion
● ${var} - Value of variable
● ${var:-default} - Use default if var is empty
● ${var:=default} - Assign default if var is empty
● ${var:+value} - Use value if var is set
● ${var:?message} - Error if var is empty
● ${#var} - Length of variable
● ${var#pattern} - Remove shortest match from beginning
● ${var##pattern} - Remove longest match from beginning
● ${var%pattern} - Remove shortest match from end
● ${var%%pattern} - Remove longest match from end
● ${var/pattern/replacement} - Replace first match
● ${var//pattern/replacement} - Replace all matches
Command Substitution
● $(command) - Run command and use output
● `command` - Older command substitution syntax
5. Wildcards and Patterns
Globbing
● * - Matches any string (including empty)
● ? - Matches any single character
● [abc] - Matches any character in brackets
● [a-z] - Matches any character in range
● [!abc] - Matches any character NOT in brackets
● {pattern1,pattern2} - Brace expansion
Examples:
ls *.txt # All .txt files
ls file?.txt # file1.txt, file2.txt, etc.
ls file[1-3].txt # file1.txt, file2.txt, file3.txt
ls file[!1].txt # All except file1.txt
echo {a,b,c}.txt # Expands to a.txt b.txt c.txt
6. Common System Commands
Process Management
● ps - Show processes
● ps aux - Show all processes
● ps -ef - Show all processes (different format)
● pgrep name - Find PID by process name
● pidof name - Get PID of process
● kill PID - Terminate process
● killall name - Kill all processes by name
● jobs - Show background jobs
● fg - Bring job to foreground
● bg - Send job to background
● nohup command & - Run command immune to hangups
File Operations
● find path -name "pattern" - Search for files
● grep pattern file - Search text in files
● sed 's/old/new/g' file - Stream editor
● awk '{print $1}' file - Pattern processing
● sort file - Sort lines
● uniq file - Remove duplicate lines
● wc -l file - Count lines
● head -n 10 file - First 10 lines
● tail -n 10 file - Last 10 lines
● tail -f file - Follow file changes
11. File and Text Commands with Options
grep - Search Text Patterns
Basic syntax: grep [options] pattern [files]
Common Options:
● -i - Case insensitive search
● -v - Invert match (show non-matching lines)
● -n - Show line numbers
● -c - Count matching lines
● -l - Show only filenames with matches
● -L - Show only filenames without matches
● -r or -R - Recursive search in directories
● -w - Match whole words only
● -x - Match whole lines only
● -o - Show only matching parts of lines
● -A n - Show n lines after match
● -B n - Show n lines before match
● -C n - Show n lines around match
● -e pattern - Use pattern (useful for multiple patterns)
● -f file - Read patterns from file
● -q - Quiet mode (no output, just exit status)
● -s - Suppress error messages
● -H - Always print filename
● -h - Never print filename
● --color - Colorize matches
Examples:
grep -i "error" logfile.txt # Case insensitive
grep -n "TODO" *.py # Show line numbers
grep -r "function" /path/to/code/ # Recursive search
grep -v "^#" config.txt # Exclude comments
grep -c "error" logfile.txt # Count matches
grep -l "main" *.c # Files containing "main"
grep -o "[0-9]\+" file.txt # Show only numbers
grep -A 3 -B 2 "error" log.txt # Context lines
grep -E "pattern1|pattern2" file.txt # Multiple patterns
cat - Display File Contents
Basic syntax: cat [options] [files]
Common Options:
● -n - Number all lines
● -b - Number non-blank lines only
● -s - Squeeze multiple blank lines into one
● -v - Show non-printing characters
● -A - Show all characters (equivalent to -vET)
● -e - Show end-of-line characters as $
● -t - Show tabs as ^I
● -E - Show line endings
● -T - Show tabs
Examples:
cat file.txt # Display file
cat -n file.txt # With line numbers
cat file1.txt file2.txt # Concatenate files
cat -s file.txt # Squeeze blank lines
cat > newfile.txt # Create new file (Ctrl+D to end)
cat >> existing.txt # Append to file
less/more - Page Through Files
Basic syntax: less [options] file or more [options] file
less Options:
● -N - Show line numbers
● -S - Don't wrap long lines
● -i - Case insensitive search
● -r - Display raw control characters
● -f - Force open even if not regular file
● -X - Don't clear screen on exit
● -F - Quit if entire file fits on screen
Navigation in less:
● Space or f - Forward one page
● b - Backward one page
● d - Forward half page
● u - Backward half page
● g - Go to beginning
● G - Go to end
● /pattern - Search forward
● ?pattern - Search backward
● n - Next search result
● N - Previous search result
● q - Quit
head - Show First Lines
Basic syntax: head [options] [files]
Common Options:
● -n num - Show first num lines (default 10)
● -c num - Show first num bytes
● -q - Quiet mode (no headers)
● -v - Verbose mode (always show headers)
Examples:
head file.txt # First 10 lines
head -n 20 file.txt # First 20 lines
head -c 100 file.txt # First 100 bytes
head -n 5 *.txt # First 5 lines of each file
tail - Show Last Lines
Basic syntax: tail [options] [files]
Common Options:
● -n num - Show last num lines (default 10)
● -c num - Show last num bytes
● -f - Follow file (watch for new lines)
● -F - Follow file, retry if file doesn't exist
● -q - Quiet mode (no headers)
● -v - Verbose mode (always show headers)
● --pid=PID - Terminate after process PID dies
Examples:
tail file.txt # Last 10 lines
tail -n 50 file.txt # Last 50 lines
tail -f logfile.txt # Follow log file
tail -F /var/log/syslog # Follow system log
tail -n +10 file.txt # From line 10 to end
wc - Word, Line, Character Count
Basic syntax: wc [options] [files]
Common Options:
● -l - Count lines
● -w - Count words
● -c - Count bytes
● -m - Count characters
● -L - Length of longest line
Examples:
wc file.txt # Lines, words, characters
wc -l file.txt # Line count only
wc -w *.txt # Word count for all txt files
ls | wc -l # Count files in directory
sort - Sort Lines
Basic syntax: sort [options] [files]
Common Options:
● -n - Numeric sort
● -r - Reverse order
● -k field - Sort by field number
● -t char - Field separator
● -u - Remove duplicates
● -f - Case insensitive
● -M - Month sort (Jan, Feb, etc.)
● -h - Human numeric sort (1K, 2M, etc.)
● -R - Random sort
● -c - Check if sorted
● -o file - Output to file
Examples:
sort file.txt # Alphabetical sort
sort -n numbers.txt # Numeric sort
sort -r file.txt # Reverse sort
sort -k2 -t: /etc/passwd # Sort by 2nd field, : separator
sort -u file.txt # Remove duplicates
sort -nr file.txt # Numeric reverse
uniq - Remove Duplicate Lines
Basic syntax: uniq [options] [input] [output]
Common Options:
● -c - Count occurrences
● -d - Show only duplicate lines
● -u - Show only unique lines
● -i - Case insensitive
● -f n - Skip first n fields
● -s n - Skip first n characters
● -w n - Compare only first n characters
Examples:
uniq file.txt # Remove consecutive duplicates
sort file.txt | uniq # Remove all duplicates
uniq -c file.txt # Count occurrences
uniq -d file.txt # Show only duplicates
cut - Extract Columns
Basic syntax: cut [options] [files]
Common Options:
● -f fields - Select fields (columns)
● -d char - Field delimiter
● -c chars - Select characters
● -b bytes - Select bytes
● --complement - Invert selection
Examples:
cut -f1,3 -d: /etc/passwd # 1st and 3rd fields, : delimiter
cut -c1-10 file.txt # Characters 1-10
cut -d' ' -f2 file.txt # 2nd field, space delimiter
cut -f1 --complement file.txt # All except 1st field
tr - Translate Characters
Basic syntax: tr [options] set1 [set2]
Common Options:
● -d - Delete characters
● -s - Squeeze repeated characters
● -c - Complement set1
● -t - Truncate set1
Examples:
tr 'a-z' 'A-Z' < file.txt # Convert to uppercase
tr -d '0-9' < file.txt # Delete digits
tr -s ' ' < file.txt # Squeeze spaces
tr '\n' ' ' < file.txt # Replace newlines with spaces
sed - Stream Editor
Basic syntax: sed [options] 'command' [files]
Common Options:
● -i - Edit in place
● -n - Suppress default output
● -e - Multiple commands
● -f script - Read commands from file
● -r or -E - Extended regex
Common Commands:
● s/old/new/ - Substitute first occurrence
● s/old/new/g - Substitute all occurrences
● d - Delete line
● p - Print line
● q - Quit
● a\text - Append text
● i\text - Insert text
Examples:
sed 's/old/new/g' file.txt # Replace all occurrences
sed -i 's/old/new/g' file.txt # Replace in place
sed -n '1,5p' file.txt # Print lines 1-5
sed '/pattern/d' file.txt # Delete matching lines
sed '2d' file.txt # Delete line 2
awk - Pattern Processing
Basic syntax: awk [options] 'program' [files]
Common Options:
● -F fs - Field separator
● -v var=value - Set variable
● -f script - Read program from file
Built-in Variables:
● NR - Number of records (line number)
● NF - Number of fields
● $0 - Entire line
● $1, $2, ... - Field values
● FS - Field separator
● OFS - Output field separator
● RS - Record separator
● ORS - Output record separator
Examples:
awk '{print $1}' file.txt # Print first field
awk -F: '{print $1,$3}' /etc/passwd # Custom separator
awk 'NR==5' file.txt # Print line 5
awk 'length > 80' file.txt # Lines longer than 80 chars
awk '{sum+=$1} END {print sum}' # Sum first column
find - Search Files and Directories
Basic syntax: find [path] [options] [expression]
Test Options:
● -name pattern - File name matches pattern
● -iname pattern - Case insensitive name
● -path pattern - Path matches pattern
● -type f/d/l - File type (file/directory/link)
● -size +/-n - File size greater/less than n
● -mtime +/-n - Modified n days ago
● -user username - Owned by user
● -group groupname - Owned by group
● -perm mode - Permission matches mode
● -empty - Empty files/directories
● -executable - Executable files
● -readable - Readable files
● -writable - Writable files
Action Options:
● -print - Print matching files (default)
● -ls - List files in ls format
● -exec command {} \; - Execute command on each file
● -delete - Delete matching files
● -ok command {} \; - Ask before executing
Examples:
find /home -name "*.txt" # Find txt files
find . -type f -size +1M # Files larger than 1MB
find /tmp -mtime +7 -delete # Delete files older than 7 days
find . -name "*.log" -exec rm {} \; # Delete all log files
find . -type f -executable # Find executable files
find . -empty -type f # Find empty files
System Information
● uname -a - System information
● whoami - Current user
● who - Logged in users
● w - Who is doing what
● uptime - System uptime
● df -h - Disk usage
● du -h - Directory usage
● free -h - Memory usage
● top - Real-time processes
● htop - Better top (if installed)
7. Exit Codes
Standard Exit Codes
● 0 - Success
● 1 - General error
● 2 - Misuse of shell command
● 126 - Command cannot execute
● 127 - Command not found
● 128 - Invalid argument to exit
● 130 - Script terminated by Ctrl+C
Testing Exit Codes
command
if [ $? -eq 0 ]; then
echo "Success"
else
echo "Failed"
fi
8. Useful Command Combinations
System Monitoring
# Find processes using most CPU
ps aux | sort -nr -k 3 | head -10
# Find processes using most memory
ps aux | sort -nr -k 4 | head -10
# Monitor file changes
tail -f /var/log/syslog
# Find large files
find / -type f -size +100M 2>/dev/null
# Check disk usage by directory
du -sh /* | sort -hr
Text Processing
# Count unique lines
sort file | uniq -c
# Find and replace in multiple files
sed -i 's/old/new/g' *.txt
# Extract specific columns
awk '{print $1,$3}' file
# Search for pattern in files
grep -r "pattern" /path/to/search
Network Commands
# Check network connectivity
ping -c 4 google.com
# Show network interfaces
ifconfig -a
# Show listening ports
netstat -tuln
# Download file
wget URL
curl -O URL
9. Conditional Statements
If Statement
if [ condition ]; then
commands
elif [ condition ]; then
commands
else
commands
fi
Case Statement
case $variable in
pattern1)
commands
;;
pattern2)
commands
;;
*)
default commands
;;
esac
10. Loops
For Loop
for var in list; do
commands
done
for ((i=1; i<=10; i++)); do
echo $i
done
While Loop
while [ condition ]; do
commands
done
Until Loop
until [ condition ]; do
commands
done
Quick Reference Examples
# Check if file exists and is readable
[ -f "$file" ] && [ -r "$file" ] && echo "File OK"
# Run command only if previous succeeded
make && make install
# Get exit status
command
status=$?
# Background process with nohup
nohup long_running_command &
# Find and kill process
pid=$(pgrep process_name)
kill $pid
# Check if variable is set
[ -n "$VAR" ] && echo "Variable is set"
# Default value for variable
VAR=${VAR:-"default_value"}