Bash Cheat Sheet

Intermediate | 15 min read | 2025.01.10

Basic Commands

File Operations

# List files
ls              # Basic
ls -la          # Detailed (including hidden files)
ls -lh          # Human-readable sizes

# Change directory
cd /path/to/dir
cd ~            # Home directory
cd -            # Previous directory
cd ..           # Parent directory

# File operations
cp file1 file2          # Copy
cp -r dir1 dir2         # Copy directory
mv file1 file2          # Move/rename
rm file                 # Delete
rm -rf dir              # Delete directory (force)
mkdir dir               # Create directory
mkdir -p a/b/c          # Create parent directories too

# File contents
cat file                # Display all
head -n 10 file         # First 10 lines
tail -n 10 file         # Last 10 lines
tail -f file            # Real-time monitoring
less file               # Pager

Text Processing

# Search
grep "pattern" file
grep -r "pattern" dir       # Recursive search
grep -i "pattern" file      # Case insensitive
grep -n "pattern" file      # Show line numbers
grep -v "pattern" file      # Exclude matches

# Replace
sed 's/old/new/' file           # First occurrence
sed 's/old/new/g' file          # All occurrences
sed -i 's/old/new/g' file       # Edit file in-place

# Column extraction
awk '{print $1}' file           # First column
awk -F: '{print $1}' file       # Specify delimiter
cut -d: -f1 file                # Delimiter and column

# Sort
sort file
sort -n file            # Numeric sort
sort -r file            # Reverse order
sort -u file            # Remove duplicates

# Duplicates
uniq file               # Remove consecutive duplicates
sort file | uniq        # Remove all duplicates
uniq -c file            # Count occurrences

# Count
wc -l file              # Line count
wc -w file              # Word count
wc -c file              # Byte count
# find
find . -name "*.txt"                    # Search by name
find . -type f -name "*.log"            # Files only
find . -type d -name "src"              # Directories only
find . -mtime -7                        # Modified within 7 days
find . -size +100M                      # Larger than 100MB
find . -name "*.tmp" -delete            # Delete matches

# locate (index-based search)
locate filename

Variables

# Variables
name="Alice"
echo $name
echo ${name}

# Environment variables
export PATH="$PATH:/new/path"
export NODE_ENV=production

# Special variables
$0      # Script name
$1      # First argument
$@      # All arguments (separate)
$*      # All arguments (as one)
$#      # Number of arguments
$?      # Exit status of last command
$$      # Process ID
$!      # PID of last background process

# String manipulation
${var:-default}     # Default value if undefined
${var:=default}     # Assign default if undefined
${#var}             # String length
${var#pattern}      # Remove pattern from start (shortest)
${var##pattern}     # Remove pattern from start (longest)
${var%pattern}      # Remove pattern from end (shortest)
${var%%pattern}     # Remove pattern from end (longest)
${var/old/new}      # Replace (first occurrence)
${var//old/new}     # Replace (all occurrences)

Control Structures

Conditionals

# if statement
if [ "$name" = "Alice" ]; then
    echo "Hello Alice"
elif [ "$name" = "Bob" ]; then
    echo "Hello Bob"
else
    echo "Hello stranger"
fi

# Conditional operators
# String
[ "$a" = "$b" ]     # Equal
[ "$a" != "$b" ]    # Not equal
[ -z "$a" ]         # Empty string
[ -n "$a" ]         # Not empty

# Numeric
[ $a -eq $b ]       # Equal
[ $a -ne $b ]       # Not equal
[ $a -lt $b ]       # Less than
[ $a -le $b ]       # Less than or equal
[ $a -gt $b ]       # Greater than
[ $a -ge $b ]       # Greater than or equal

# File
[ -e file ]         # Exists
[ -f file ]         # Is a file
[ -d dir ]          # Is a directory
[ -r file ]         # Is readable
[ -w file ]         # Is writable
[ -x file ]         # Is executable

# Logical operations
[ cond1 ] && [ cond2 ]    # AND
[ cond1 ] || [ cond2 ]    # OR
! [ cond ]                # NOT

# [[ ]] usage (extended test)
[[ $name == A* ]]         # Pattern matching
[[ $name =~ ^A.*$ ]]      # Regex matching

Loops

# for
for i in 1 2 3 4 5; do
    echo $i
done

for i in {1..10}; do
    echo $i
done

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

for ((i=0; i<10; i++)); do
    echo $i
done

# while
while [ $count -lt 10 ]; do
    echo $count
    ((count++))
done

# Read from file
while read line; do
    echo $line
done < file.txt

case

case $option in
    start)
        echo "Starting..."
        ;;
    stop)
        echo "Stopping..."
        ;;
    restart)
        echo "Restarting..."
        ;;
    *)
        echo "Unknown option"
        ;;
esac

Functions

# Function definition
greet() {
    local name=$1
    echo "Hello, $name!"
    return 0
}

# Call
greet "Alice"

# Capture return value
result=$(greet "Alice")
status=$?

Redirection & Pipes

# Output redirection
command > file          # Overwrite
command >> file         # Append
command 2> file         # Standard error
command &> file         # Both stdout and stderr

# Input redirection
command < file

# Pipes
command1 | command2
ls | grep "txt" | wc -l

# Here Document
cat << EOF
Multi-line
text
EOF

# Process substitution
diff <(command1) <(command2)

Useful Techniques

# Command substitution
date=$(date +%Y%m%d)
files=$(ls *.txt)

# Arithmetic operations
((result = 5 + 3))
result=$((5 + 3))

# Background execution
command &
nohup command &         # Continue after logout

# Command chaining
command1 && command2    # Execute next only on success
command1 || command2    # Execute next only on failure
command1 ; command2     # Always execute both

# xargs
find . -name "*.txt" | xargs grep "pattern"
find . -name "*.tmp" | xargs rm

# tee
command | tee file      # Output to both screen and file

Shell Script Example

#!/bin/bash
set -e  # Stop on error
set -u  # Error on undefined variables

# Check arguments
if [ $# -lt 1 ]; then
    echo "Usage: $0 <filename>"
    exit 1
fi

# Check file existence
if [ ! -f "$1" ]; then
    echo "File not found: $1"
    exit 1
fi

# Process
echo "Processing $1..."
← Back to list