🐧 Linux Commands
Linux & Bash Complete Cheatsheet
File system, permissions, processes, networking, bash scripting and SSH — complete Linux reference.
📖 10 sections
⏱ 22 min read
✅ Quizzes included
🌙 Dark mode
01 Navigation & Files
BASHNavigation and file operations
# Navigation
pwd                    # current directory
ls -la                 # list all files with details
cd /path/to/dir        # change directory
cd ~                   # home directory
cd ..                  # parent directory
cd -                   # previous directory

# Files & directories
mkdir -p dir/sub/dir   # create nested directories
touch file.txt         # create empty file
cp -r source/ dest/    # copy directory recursively
mv old.txt new.txt     # move/rename
rm -rf folder/         # delete directory (careful!)
ln -s /path link       # symbolic link

# View files
cat file.txt           # show content
less file.txt          # paginated view (q to quit)
head -20 file.txt      # first 20 lines
tail -f logfile.log    # follow log in real-time
wc -l file.txt         # count lines
⚠️
rm -rf deletes immediately, no recycle bin. DOUBLE-CHECK before running, especially as root!
02 File Permissions
BASHFile permissions
# Format: -rwxrwxrwx (type)(owner)(group)(others)
ls -l file.txt         # view permissions

# chmod: r=4, w=2, x=1
chmod 755 script.sh    # rwxr-xr-x
chmod 644 file.txt     # rw-r--r--
chmod +x script.sh     # add execute for all
chmod u+w file.txt     # add write for owner
chmod o-r file.txt     # remove read from others

# Ownership
chown user:group file.txt
chown -R www-data /var/www/

# Special permissions
chmod 4755 file        # setuid bit (runs as owner)
chmod 1755 dir         # sticky bit (only owner deletes)

# Check effective permissions
id                     # show current user + groups
sudo -l               # list sudo permissions
r (4)
Read file / list directory
w (2)
Write file / create files in dir
x (1)
Execute file / enter directory
755
Owner: rwx, Group: r-x, Others: r-x
644
Owner: rw-, Group: r--, Others: r--
03 Process Management
BASHProcess management
# View processes
ps aux                 # all processes with details
top                    # interactive process monitor
htop                   # better interactive monitor
pgrep nginx            # find process ID by name
kill 1234              # send SIGTERM to PID 1234
kill -9 1234           # force kill (SIGKILL)
killall nginx          # kill all processes by name
pkill -f 'python app'  # kill by pattern

# Background jobs
command &              # run in background
command &> output.log  # background with logging
jobs                   # list background jobs
fg %1                  # bring job 1 to foreground
bg %1                  # resume job 1 in background

# System resources
free -h                # memory usage
df -h                  # disk space
du -sh /var/log/       # directory size
lsof -i :3000          # what's using port 3000
netstat -tlnp          # listening ports
💡
Use 'nohup command &' to keep processes running after you log out.
04 Searching & Finding
BASHFind and search
# find files
find / -name 'file.txt'          # find by name
find . -name '*.py'              # find by extension
find . -mtime -7                 # modified last 7 days
find . -size +100M               # files >100MB
find . -type f -exec chmod 644 {} \;  # find + execute

# grep - search content
grep 'error' logfile.log         # search in file
grep -r 'TODO' ./src/            # recursive search
grep -i 'error' file.txt         # case-insensitive
grep -n 'error' file.txt         # show line numbers
grep -v 'success' file.txt       # invert match (exclude)
grep -c 'error' file.txt         # count matches

# which / whereis
which python3                    # find executable path
whereis nginx                    # find binary + docs
type ls                          # how command is resolved

# locate (fast, uses index)
locate file.txt
updatedb                         # update locate database
05 Text Processing
BASHText processing powertools
# awk - column processing
awk '{print $1, $3}' file.txt          # print col 1 and 3
awk -F: '{print $1}' /etc/passwd       # custom delimiter
awk '/error/ {print}' log.txt          # print matching lines
awk '{sum+=$1} END{print sum}' nums.txt # sum a column

# sed - stream editor
sed 's/old/new/g' file.txt             # replace all
sed -i 's/foo/bar/g' file.txt          # in-place edit
sed '/pattern/d' file.txt             # delete matching lines
sed -n '5,10p' file.txt               # print lines 5-10

# sort & uniq
sort file.txt                          # alphabetic sort
sort -n numbers.txt                    # numeric sort
sort -r file.txt                       # reverse
sort file.txt | uniq                   # unique lines
sort file.txt | uniq -c                # count occurrences

# cut & paste
cut -d',' -f1,3 data.csv              # extract columns
cut -c1-10 file.txt                   # extract characters

# xargs
find . -name '*.log' | xargs rm       # delete found files
cat urls.txt | xargs curl -O          # download all URLs
06 Networking
BASHNetworking commands
# Connectivity
ping google.com                 # test connectivity
ping -c 4 google.com            # 4 pings only
traceroute google.com           # trace route
dig google.com                  # DNS lookup
nslookup google.com             # DNS query
curl https://api.example.com    # HTTP request
curl -X POST -H 'Content-Type: application/json' \
  -d '{"key":"val"}' https://api.example.com
wget https://file.com/file.zip  # download file

# Network info
ip addr                         # IP addresses
ifconfig                        # network interfaces (older)
ss -tlnp                        # listening sockets
netstat -tlnp                   # same (older)
nmap -sV target.com             # port scan

# Firewall (ufw)
ufw status
ufw allow 22
ufw allow 80/tcp
ufw deny 23
ufw enable
💡
Use 'curl -I url' to see HTTP headers only, 'curl -v url' for verbose (shows request+response).
07 Package Management
BASHPackage management
# Debian/Ubuntu (apt)
apt update                      # refresh package index
apt upgrade                     # upgrade all packages
apt install nginx               # install package
apt remove nginx                # remove package
apt purge nginx                 # remove + config files
apt autoremove                  # remove unused dependencies
apt search nginx                # search packages
apt show nginx                  # package details

# Red Hat/CentOS (yum/dnf)
dnf install nginx
dnf update
dnf remove nginx

# Python
pip3 install requests
pip3 install -r requirements.txt
pip3 list
pip3 freeze > requirements.txt

# Node.js
npm install -g pm2
npm update

# Snap (universal)
snap install code --classic
snap list
08 Bash Scripting
BASHBash scripting
#!/bin/bash
# Variables
NAME="Ali"
echo "Hello $NAME"
READONLY MAX=100
LINES=$(wc -l < file.txt)  # command substitution

# Conditionals
if [ $AGE -gt 18 ]; then
  echo "Adult"
elif [ $AGE -eq 18 ]; then
  echo "Just 18"
else
  echo "Minor"
fi

# Loops
for i in {1..5}; do echo $i; done
for file in *.txt; do echo $file; done
while [ $COUNT -lt 10 ]; do
  COUNT=$((COUNT+1))
done

# Functions
greet() {
  local name=$1  # local variable
  echo "Hello, $name!"
  return 0
}
greet "Ali"

# Arrays
FRUITS=(apple banana cherry)
echo ${FRUITS[0]}
echo ${#FRUITS[@]}  # length
for fruit in "${FRUITS[@]}"; do echo $fruit; done
$?
Exit code of last command (0=success)
$0
Script name
$1 $2...
Positional arguments
$@
All arguments
$$
Current process PID
$!
Last background PID
09 SSH & Security
BASHSSH and security
# Connect
ssh user@hostname
ssh -p 2222 user@hostname      # custom port
ssh -i ~/.ssh/key.pem user@host # specific key

# Key management
ssh-keygen -t ed25519 -C "comment"   # generate key pair
ssh-copy-id user@hostname             # copy public key to server
cat ~/.ssh/id_ed25519.pub             # view public key

# SSH config (~/.ssh/config)
Host myserver
  HostName 192.168.1.100
  User ubuntu
  Port 22
  IdentityFile ~/.ssh/key.pem

# Then just: ssh myserver

# File transfer
scp file.txt user@host:/path/
scp -r folder/ user@host:/path/
rsync -avz source/ user@host:/dest/  # efficient sync

# Security hardening (/etc/ssh/sshd_config)
PermitRootLogin no
PasswordAuthentication no
Port 2222
AllowUsers ubuntu
💡
Always use SSH keys instead of passwords. Disable root login and password auth for any public server.
10 Mini Quizzes
❓ Quiz 1
What does 'chmod 755 script.sh' set?
755 = 7(rwx) for owner, 5(r-x) for group, 5(r-x) for others. 7=4+2+1=rwx, 5=4+1=r-x.
❓ Quiz 2
What does 'tail -f logfile.log' do?
-f means 'follow' — it keeps running and prints new lines as they're appended. Essential for monitoring live logs.