Complete Bash Cheatsheet

Everything you need to work efficiently in the terminal

Quick Reference

Bash is the default shell on most Linux distributions and macOS. This cheatsheet covers all essential commands.

pwd
Print working directory - shows your current location in the filesystem
$ pwd
# Output: /home/user/documents
cd [directory]
Change directory - move to a different folder
cd /path/to/dir # Absolute path
cd .. # Move up one level
cd ~ # Home directory
cd - # Previous directory
ls [options] [directory]
List directory contents - view files and folders
ls -l # Long format with details
ls -a # Show hidden files
ls -lh # Human-readable file sizes
ls -t # Sort by modification time
ls -R # Recursive listing

2 File Operations

touch filename
Create empty file or update file timestamp
touch file.txt
touch -t 202301010000 oldfile.txt # Set specific timestamp
cp [options] source destination
Copy files and directories
cp file1 file2
cp -r dir1 dir2 # Recursive copy
cp -i file* dir # Interactive (prompt before overwrite)
cp -v file.txt backup/ # Verbose output
mv [options] source destination
Move or rename files and directories
mv oldname newname
mv file1 file2 dir/
mv -n file.txt destination/ # No overwrite
rm [options] file
Remove files and directories (use with caution!)
rm file.txt
rm -r dir/ # Recursive remove
rm -f file # Force remove (no prompt)
rm -i file* # Interactive remove (prompt)
mkdir [options] directory
Create directories
mkdir newdir
mkdir -p path/to/newdir # Create parent directories as needed
mkdir -m 755 protected_dir # With specific permissions
chmod [options] permissions file
Change file permissions
chmod 755 script.sh
chmod +x executable # Add execute permission
chmod -R 644 dir/ # Recursive permission change
chmod u=rw,go=r file.txt # Symbolic permissions
chown [options] user:group file
Change file owner and group
chown user:group file.txt
chown -R www-data:www-data /var/www # Recursive ownership
chown root: /etc/passwd # Set root owner with default group
find [path] [options] [expression]
Search for files in directory hierarchy
find /home -name "*.txt"
find . -type f -size +1M # Files larger than 1MB
find /var/log -mtime -7 # Modified in last 7 days
find . -name "temp*" -exec rm {} \; # Find and delete

3 Text Processing

cat [options] file
Concatenate and display file contents
cat file.txt
cat file1 file2 > combined
cat -n file.txt # Show line numbers
cat -v nonprint.txt # Display non-printing characters
grep [options] pattern [file]
Search for patterns in files (Global Regular Expression Print)
grep "error" logfile.txt
grep -r "TODO" src/ # Recursive search
grep -i "warning" file.log # Case insensitive
grep -v "success" results.csv # Invert match
grep -E "[0-9]{3}-[0-9]{4}" contacts.txt # Extended regex
sed [options] 'command' file
Stream editor for filtering and transforming text
sed 's/old/new/g' file.txt # Replace text globally
sed -i.bak 's/foo/bar/' config.ini # In-place edit with backup
sed '/^#/d' script.sh # Delete comment lines
sed -n '5,10p' longfile.txt # Print lines 5-10
awk 'pattern {action}' file
Powerful text processing and data extraction
awk '{print $1}' file.txt # Print first column
awk -F',' '{print $2}' data.csv # CSV processing
awk '$3 > 100 {print $0}' data.txt # Filter rows
awk 'BEGIN {sum=0} {sum+=$1} END {print sum}' numbers.txt # Sum column
head [options] file
Display first part of files
head file.txt # First 10 lines
head -n 20 log.txt # First 20 lines
head -c 100 data.bin # First 100 bytes
tail [options] file
Display last part of files
tail file.log # Last 10 lines
tail -n 20 access.log # Last 20 lines
tail -f /var/log/syslog # Follow log in real-time
sort [options] file
Sort lines of text files
sort names.txt # Alphabetical sort
sort -n numbers.txt # Numerical sort
sort -r data.txt # Reverse sort
sort -u duplicates.txt # Unique sort
uniq [options] file
Report or omit repeated lines
uniq duplicates.txt # Remove consecutive duplicates
uniq -c log.txt # Count occurrences
uniq -d repeated.txt # Only show duplicates
wc [options] file
Word count
wc file.txt # Lines, words, characters
wc -l *.log # Count lines in each log file
wc -c binary.dat # Count bytes

4 System Information

uname [options]
Print system information
uname -a # All system info
uname -s # Kernel name
uname -r # Kernel release
df [options]
Disk space usage
df -h # Human-readable sizes
df -i # Inode usage
df -T /dev/sda1 # Filesystem type
du [options] [file]
Estimate file space usage
du -sh /home # Summary of directory size
du -ah --max-depth=1 # All files one level deep
du -BM /var/log # Sizes in megabytes
free [options]
Display memory usage
free -h # Human-readable output
free -m # Show in megabytes
free -s 5 # Continuous display every 5 seconds
top
Display Linux processes
top # Interactive process viewer
top -u apache # Show only apache processes
top -n 1 -b > processes.txt # Save snapshot
uptime
Show how long system has been running
uptime # Output: 14:30:45 up 3 days, 2:30, 3 users, load average: 0.15, 0.10, 0.05

5 Processes

ps [options]
Report a snapshot of current processes
ps aux # Show all processes
ps -ef # Full format listing
ps -u root # Processes by user
ps --forest # Show process hierarchy
kill [options] PID
Terminate processes by ID
kill 1234 # Terminate process 1234
kill -9 5678 # Force kill process
kill -l # List all signals
pkill [options] pattern
Kill processes by name
pkill firefox # Kill all firefox processes
pkill -u bob # Kill all processes owned by bob
pkill -f "python script.py" # Kill by full command
bg [job_spec]
Resume suspended jobs in background
bg %1 # Resume job 1 in background
bg # Resume current job
fg [job_spec]
Bring jobs to foreground
fg %2 # Bring job 2 to foreground
fg # Bring current job to foreground

6 Networking

ping [options] host
Send ICMP ECHO_REQUEST to network hosts
ping google.com # Continuous ping
ping -c 4 8.8.8.8 # Ping 4 times
ping -i 5 example.org # Ping every 5 seconds
ifconfig [interface]
Configure network interfaces (deprecated, use ip instead)
ifconfig # List all interfaces
ifconfig eth0 up # Bring interface up
ifconfig eth0 192.168.1.100 # Set IP address
netstat [options]
Print network connections, routing tables, interface statistics
netstat -tulnp # Listening ports
netstat -r # Routing table
netstat -s # Statistics by protocol
ssh [options] [user@]hostname
OpenSSH SSH client (remote login program)
ssh user@example.com # Basic login
ssh -p 2222 admin@server # Custom port
ssh -i ~/.ssh/key.pem ubuntu@aws-server # With identity file

7 Scripting

#!/bin/bash
Shebang line to make file executable as bash script
#!/bin/bash
echo "Hello World"
Variables
Variable declaration and usage
name="John" # Assign value
echo $name # Access variable
readonly PI=3.14 # Read-only variable
unset name # Delete variable
Conditionals
If/else statements
if [ $age -gt 18 ]; then
  echo "Adult"
elif [ $age -gt 12 ]; then
  echo "Teen"
else
  echo "Child"
fi
Loops
For and while loops
# For loop
for i in {1..5}; do
  echo "Number: $i"
done

# While loop
count=1
while [ $count -le 5 ]; do
  echo "Count: $count"
  ((count++))
done
Functions
Define and call functions
greet() {
  local name=$1
  echo "Hello, $name"
}

greet "Alice" # Call function
Command-line arguments
Access script arguments
echo "Script name: $0"
echo "First arg: $1"
echo "All args: $@"
echo "Arg count: $#"
echo "Last exit status: $?"
Debugging
Debug bash scripts
bash -x script.sh # Trace execution
set -x # Enable debugging
set +x # Disable debugging
trap 'echo Error at line $LINENO' ERR # Error handling

8 Keyboard Shortcuts

Ctrl + A
Move cursor to beginning of line
Ctrl + E
Move cursor to end of line
Ctrl + U
Delete from cursor to beginning of line
Ctrl + K
Delete from cursor to end of line
Ctrl + W
Delete previous word
Ctrl + R
Search command history
Ctrl + C
Terminate current command
Ctrl + Z
Suspend current command (use fg to resume)
Ctrl + D
Exit shell (when on empty line)
Tab
Auto-complete file or command
!!
Repeat last command
!command
Run most recent command starting with 'command'