MaisTools
Developer/

Linux Cheat Sheet

Quick Linux reference: terminal commands, flags, examples and pipe combinations, organised by section with instant search.

Linux Cheat Sheet

Terminal commands, bash, pipes and one-liners

Navigation

ls

Lists the contents of a directory with permissions, size and date.

Flags-l-a-la-h-S-t-r-R
Example
ls -la /var/log
cd

Changes the current directory. Without arguments goes to home.

Example
cd /etc/nginx
cd ~
cd -
cd ..
pwd

Prints the full path of the current directory.

Flags-P-L
Example
pwd
tree

Shows the directory tree in visual form.

Flags-L-d-a-I
Example
tree -L 2 ~/projects
file

Identifies the type of a file (text, binary, image, script, etc).

Flags-i-b
Example
file image.png
file -i script.sh
stat

Shows detailed metadata of a file (size, inode, dates, permissions).

Flags-c-f
Example
stat file.txt
stat -c "%n %s %y" file.txt

Files

touch

Creates an empty file or updates the modification timestamp.

Flags-a-m-c-t
Example
touch newfile.txt
touch -t 202601011200 file.txt
mkdir

Creates a directory. With -p creates the full parent path if missing.

Flags-p-m-v
Example
mkdir -p projects/app/src
mkdir -m 700 secret
rmdir

Removes an empty directory.

Flags-p
Example
rmdir empty_dir
rmdir -p a/b/c
rm

Removes files or directories. With -rf removes recursively without confirmation (dangerous).

Flags-r-f-i-v
Example
rm file.txt
rm -rf node_modules
cp

Copies files or directories.

Flags-r-v-i-p-a-u
Example
cp file.txt backup.txt
cp -r src/ dest/
mv

Moves or renames files and directories.

Flags-i-v-n-f
Example
mv old.txt new.txt
mv *.log archive/
ln

Creates links: -s for symbolic, no flag for hard link.

Flags-s-f-v
Example
ln -s /usr/local/bin/node ~/node
ln file hardlink
cat

Prints the contents of one or more files to stdout.

Flags-n-A-b-s
Example
cat file.txt
cat -n script.sh
less

Pages through files with navigation. Search with /. +F follows like tail -f.

Flags-N-S-X+F
Example
less /var/log/syslog
less +F app.log
head

Shows the first N lines of a file (default: 10).

Flags-n-c
Example
head -n 20 file.txt
head -c 1024 binary
tail

Shows the last N lines. -f follows the file as it grows.

Flags-n-f-F-c
Example
tail -n 50 access.log
tail -f /var/log/syslog
wc

Counts lines (-l), words (-w), bytes (-c) or characters (-m).

Flags-l-w-c-m
Example
wc -l file.txt
wc *.md

Permissions

chmod

Changes file and directory permissions (rwx).

Flags-R-v
Example
chmod 755 script.sh
chmod +x deploy.sh
chmod -R 644 docs/
chown

Changes the owner and/or group of files.

Flags-R-v
Example
chown user file.txt
chown -R www-data:www-data /var/www
sudo

Runs a command as another user (root by default).

Flags-i-u-k-l
Example
sudo apt update
sudo -u postgres psql
sudo -i
su

Switches to another user. - loads that user's environment.

Flags--c-l
Example
su - postgres
su -c 'whoami' root
useradd / userdel

Creates (useradd) or deletes (userdel) user accounts.

Flags-m-s-G-r
Example
sudo useradd -m -s /bin/bash john
sudo userdel -r john
passwd

Sets or changes a user's password.

Flags-l-u-d
Example
passwd
sudo passwd john
whoami / who

Shows the current user (whoami) or all logged-in users (who).

Example
whoami
who
who -a
id / groups

Shows the current user's UID, GID and group memberships.

Flags-u-g-G-n
Example
id
id -nG
groups

Processes

ps

Lists processes. aux shows all processes with detail.

Flagsaux-ef-u--sort
Example
ps aux
ps -ef
top

Shows processes in real time, sorted by CPU/memory usage.

Flags-u-p-d-n
Example
top
top -u www-data
top -p 1234
kill

Sends a signal to a process by PID. -9 forces termination (SIGKILL).

Flags-9-15-l-HUP
Example
kill 1234
kill -9 1234
kill -HUP $(pidof nginx)
killall / pkill

Kills processes by name (killall) or pattern (pkill).

Flags-9-u-i
Example
killall firefox
pkill -9 -f node
pkill -u john
jobs / fg / bg

Manages shell jobs: jobs lists them, fg brings to foreground, bg resumes in background.

Flags-l-r-s
Example
jobs
fg %1
bg %2
# Ctrl+Z to suspend the foreground job
nohup

Runs a command that keeps running after closing the terminal.

Example
nohup ./long-task.sh > out.log 2>&1 &
nohup python script.py &
nice / renice

Starts a process with adjusted priority (nice) or changes the priority (renice).

Flags-n
Example
nice -n 19 ./heavy.sh
renice -n 5 -p 1234
& (background)

Appending & at the end of a command runs it in background, freeing the terminal.

Example
./server.sh &
long-task &
disown %1

Network

ping

Tests connectivity by sending ICMP packets. -c limits the count.

Flags-c-i-W-s
Example
ping google.com
ping -c 4 8.8.8.8
curl

Makes HTTP/HTTPS requests and downloads files. Supports GET, POST, headers, authentication.

Flags-X-H-d-o-O-L-I-s-u
Example
curl https://api.github.com
curl -X POST -H "Content-Type: application/json" -d '{"a":1}' url
curl -O https://example.com/file.zip
wget

Downloads files via HTTP/FTP. Supports resume with -c and recursive mirroring.

Flags-c-r-O-q--mirror
Example
wget https://example.com/file.zip
wget -c <url>
wget -r -np https://site/docs/
ssh

Connects to a remote server via Secure Shell. -L creates tunnels for local ports.

Flags-p-i-L-R-D-N-T
Example
ssh user@host
ssh -p 2222 -i ~/.ssh/id_ed25519 user@host
ssh -L 8080:localhost:80 user@host
scp

Copies files between machines via SSH.

Flags-r-P-i-p
Example
scp file.txt user@host:/tmp/
scp -r dir/ user@host:/var/www/
scp user@host:/etc/conf .
rsync

Synchronises files and directories efficiently. -avz is the most common combination.

Flags-a-v-z-P--delete--exclude
Example
rsync -avz src/ user@host:/dest/
rsync -av --delete --exclude='.git' a/ b/
ss / netstat

Shows listening ports and active connections. -tulpn is the typical usage.

Flags-t-u-l-n-p
Example
ss -tulpn
ss -t state established
dig / nslookup / host

Queries DNS. dig is more detailed, nslookup simpler, host more concise.

Flags+short-t@
Example
dig google.com
dig +short MX gmail.com
nslookup example.com 8.8.8.8

Compression

tar

Packs and compresses directories. -czf creates with gzip, -xzf extracts.

Flags-c-x-z-j-J-v-f-t
Example
tar -czvf archive.tar.gz folder/
tar -xzvf archive.tar.gz
tar -tf archive.tar.gz
zip / unzip

Zip compression. unzip -l lists contents without extracting.

Flags-r-q-l-d
Example
zip -r out.zip folder/
unzip archive.zip
unzip -l archive.zip
gzip / gunzip

Compresses/decompresses individual files with gzip. -k keeps the original.

Flags-d-k-9-r
Example
gzip file.txt
gzip -d file.txt.gz
gzip -k file.txt
bzip2 / bunzip2

Bzip2 compression, slower but with better ratio than gzip.

Flags-d-k-9
Example
bzip2 file.txt
bunzip2 file.txt.bz2
xz / unxz

Xz compression, even better ratio. -T0 uses all cores.

Flags-d-k-9-T
Example
xz file.txt
unxz file.txt.xz
xz -T0 file
7z

7z format, high compression ratio. Supports password and split archives.

Subcommandsaxl
Flags-p
Example
7z a out.7z folder/
7z x archive.7z
7z a -p out.7z secret.txt

Search

find

Searches files by name, type, size, age, and runs actions with -exec.

Flags-name-type-size-mtime-exec-delete-empty
Example
find . -name "*.log"
find / -type f -size +100M
find . -mtime -7
find . -name "*.tmp" -delete
grep

Searches patterns in files. -r recursive, -i case-insensitive, -E enables regex.

Flags-r-i-n-v-l-E-c-A-B-C
Example
grep -rn "TODO" src/
grep -i error log
grep -E "warn|error" file
awk

Processes text column by column. Full language for parsing structured files.

Example
awk '{print $1}' file.txt
awk -F',' '{print $2}' csv
awk '/error/ {count++} END {print count}' log
sed

Edits text streams. -i edits files in place, mostly used for substitutions.

Flags-i-e-n-E
Example
sed 's/old/new/g' file
sed -i 's/old/new/g' file
sed -n '10,20p' file
locate / which / whereis

Finds binaries and files: locate (cache), which (in PATH), whereis (binary, source, manual).

Flags-i-l
Example
locate nginx.conf
which python3
whereis bash

Redirection

> (redirect stdout)

Redirects stdout to a file, overwriting existing content.

Example
echo hello > out.txt
ls -la > files.txt
>> (append stdout)

Redirects stdout to a file, appending to existing content.

Example
echo "line" >> log.txt
date >> events.log
| (pipe)

Connects stdout of one command to stdin of the next, chaining processes.

Example
ls -la | grep .conf
cat file | sort | uniq
2> (redirect stderr)

Redirects stderr (fd 2). 2>&1 merges stderr into stdout. &> does both in bash.

Example
cmd 2> errors.log
cmd > out.log 2>&1
cmd &> all.log
tee

Reads from stdin and writes to a file AND to stdout. -a appends instead of overwriting.

Flags-a
Example
ls | tee files.txt
echo 'data' | sudo tee /etc/conf
make | tee -a build.log
xargs

Builds commands from stdin. Indispensable for combining find or grep with other commands.

Flags-n-I-P-0
Example
find . -name "*.log" | xargs rm
echo "a b c" | xargs -n 1
ls *.txt | xargs -I {} cp {} backup/

Environment

export

Sets environment variables that are inherited by child processes.

Example
export PATH="$PATH:/opt/bin"
export API_KEY="abc123"
export -p
env / printenv

Lists all active environment variables. printenv can show a specific one.

Example
env
printenv PATH
env VAR=value command
alias / unalias

Creates command shortcuts. Set in ~/.bashrc or ~/.zshrc to make permanent.

Example
alias ll='ls -la'
alias gs='git status'
unalias ll
echo

Prints text or variables to stdout. -e enables escapes like \n and \t.

Flags-n-e
Example
echo "Hello $USER"
echo -e "line1\nline2"
echo $PATH
source / .

Loads a script in the current shell (not a subshell). Useful for .bashrc and venv.

Example
source ~/.bashrc
. ~/.zshrc
source venv/bin/activate
history

Shows command history. !! repeats the last, !N runs command N.

Flags-c-d!
Example
history
history | grep ssh
!!
!42

Packages

apt / apt-get

Debian/Ubuntu package manager. apt is more modern and friendly than apt-get.

Subcommandsupdateupgradeinstallremovepurgesearchshow
Example
sudo apt update && sudo apt upgrade
sudo apt install nginx
sudo apt remove --purge package
apt search keyword
yum / dnf

Red Hat/Fedora/CentOS package manager. dnf is the modern successor of yum.

Subcommandsinstallremoveupdatesearchinfolist
Example
sudo dnf install nginx
sudo yum update
dnf search keyword
brew

Package manager for macOS and Linux with community-maintained formulae.

Subcommandsinstalluninstallupdateupgradesearchlist
Example
brew install wget
brew update && brew upgrade
brew list
brew search node
pacman

Arch Linux package manager. -Syu updates everything, -S installs, -R removes.

Flags-S-R-Syu-Ss-Q
Example
sudo pacman -S nginx
sudo pacman -Syu
pacman -Ss keyword
snap / flatpak

Universal sandboxed packages. Install on any modern distribution.

Subcommandsinstallremovelistfind
Example
sudo snap install code
flatpak install flathub org.gimp.GIMP
snap list

SSH

ssh-keygen

Generates SSH key pairs. ed25519 is the current recommendation (faster and safer than RSA).

Flags-t-b-C-f-N
Example
ssh-keygen -t ed25519 -C "john.doe@example.com"
ssh-keygen -t rsa -b 4096
ssh-copy-id

Copies the public key to the remote server's ~/.ssh/authorized_keys.

Flags-i-p
Example
ssh-copy-id user@host
ssh-copy-id -i ~/.ssh/id_ed25519.pub -p 2222 user@host
ssh-agent / ssh-add

SSH agent keeps decrypted keys in memory so passphrase isn't asked on every connection.

Flags-l-d-D
Example
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519
ssh-add -l
sftp

Interactive SFTP client to transfer files via SSH.

Example
sftp user@host
put file.txt
get remote.zip
ls
bye
~/.ssh/config

Per-host SSH config file. Allows alias, identity, port and jump host configuration.

Example
Host myserver
  HostName 1.2.3.4
  User john
  Port 2222
  IdentityFile ~/.ssh/id_ed25519

Disk

df

Shows used and available space per filesystem. -h in human-readable format.

Flags-h-T-i
Example
df -h
df -h /
df -i
du

Shows space used by files and directories. -sh summary in human-readable format.

Flags-h-s-a-c--max-depth
Example
du -sh *
du -h --max-depth=1
du -ah . | sort -rh | head -20
mount / umount

Mounts a filesystem at a mount point. umount unmounts.

Flags-a-t-o
Example
mount
sudo mount /dev/sdb1 /mnt/data
sudo umount /mnt/data
lsblk / fdisk

Lists disks and partitions in tree (lsblk) or table (fdisk) format.

Flags-f-l-p
Example
lsblk
lsblk -f
sudo fdisk -l
free

Shows total, used, free and cached RAM. -h in human-readable format.

Flags-h-m-g-s
Example
free -h
free -m
free -h -s 2

Monitoring

htop

Improved version of top with colors, scroll, and kills processes with F9.

Flags-u-p
Example
htop
htop -u www-data
htop -p 1234,5678
vmstat

Virtual memory, CPU and IO statistics. Useful for diagnosing bottlenecks.

Example
vmstat
vmstat 2 5
iostat

Disk IO statistics. Identifies saturated disks.

Flags-x-c-d
Example
iostat
iostat -xz 2
dmesg

Shows kernel messages. Useful for diagnosing hardware or driver problems.

Flags-T-w-l
Example
sudo dmesg | tail
sudo dmesg -T
sudo dmesg -w
systemctl

Controls systemd services: start, stop, status, enable on boot.

Subcommandsstartstoprestartstatusenabledisablereload
Example
sudo systemctl start nginx
sudo systemctl status sshd
sudo systemctl enable docker
journalctl

systemd logs. -f follows live, -u filters by service, --since by time.

Flags-u-f-n--since-p
Example
journalctl -u nginx
journalctl -f
journalctl --since "1 hour ago"
journalctl -p err
uptime / w

uptime shows how long the system has been running and the load average. w lists logged-in users and what they are doing.

Example
uptime
w

Advanced

watch

Repeats a command periodically. -d highlights changes between runs.

Flags-n-d-t
Example
watch -n 2 "df -h"
watch -d "ls -l"
watch "ps aux | grep node"
screen

Creates persistent terminal sessions that survive logouts. Classic version.

Flags-S-r-ls-d
Example
screen -S work
screen -r work
screen -ls
# Ctrl+A D to detach
tmux

Modern terminal multiplexer: multiple windows, panes and persistent sessions.

Subcommandsnewattachlskill-session
Example
tmux new -s work
tmux attach -t work
tmux ls
# Ctrl+B D to detach
cron / crontab

Periodic task scheduler. crontab -e edits the current user's jobs.

Flags-e-l-r
Example
crontab -e
crontab -l
0 3 * * * /script.sh    # daily at 3am
*/15 * * * * /poll.sh   # every 15 minutes
at

Schedules a command to run only once at a future time.

Flags-l-r-c
Example
echo "/script.sh" | at now + 1 hour
at 14:30 tomorrow
atq
at -r 5

Reference

stdin, stdout, stderr

Every process has three default streams identified by file descriptors. Understanding these streams is the key to combining commands with pipes and redirections.

stdinfd 0

Standard input. By default comes from the keyboard, but can be replaced by a file with < or by the stdout of another command via pipe.

stdoutfd 1

Standard output. By default goes to the terminal. Redirected with > (overwrite) or >> (append).

stderrfd 2

Errors and warnings. A separate stream so errors don't mix with normal output. Redirected with 2>.

Example
cmd > out.txt          # stdout → file
cmd 2> err.txt         # stderr → file
cmd > out 2>&1         # stdout + stderr → file
cmd &> all.txt         # bash shorthand
cmd < input.txt        # stdin ← file
cmd1 | cmd2            # stdout cmd1 → stdin cmd2
rwx permissions

Every file has three permission groups (user, group, others) with three bits each (read, write, execute). In numeric form each group is the sum of its bits.

Targets
  • ufile owner
  • gfile group
  • oeveryone else
  • aall (u+g+o)
Bits and values
  • r = 4 — read
  • w = 2 — write
  • x = 1 — execute (or enter directory)
Common examples
chmod 755 file       # rwx r-x r-x   (typical script)
chmod 644 file       # rw- r-- r--   (regular file)
chmod 600 file       # rw- --- ---   (private, e.g. SSH key)
chmod 700 dir        # rwx --- ---   (private dir)
chmod +x script.sh   # add execute for everyone
chmod u+w,g-w file   # add write to owner, remove from group
chmod -R 755 dir/    # recursive
Foreground vs Background

The shell can run multiple jobs at once. Only the foreground job uses the terminal; background jobs keep running while you type other commands.

Foreground

Job using the terminal. Receives keyboard input and shows output. Blocks the prompt until it finishes.

Background

Job running in parallel, not occupying the terminal. Frees the prompt for other commands. Stop it with kill or by bringing it to fg.

Useful commands
./long-task.sh &     # start in background
Ctrl+Z               # suspend the foreground job
jobs                 # list jobs of the current shell
fg %1                # bring job 1 to foreground
bg %1                # resume job 1 in background
disown %1            # detach from shell (survives logout)
nohup ./task.sh &    # ignore HUP, redirect to nohup.out
ps -ef               # list all system processes
20 essential one-liners

Common command combinations for daily work. Each solves a specific task in a single pipeline.

  • 01.Find files larger than 100MB across the whole system.
    find / -type f -size +100M 2>/dev/null
  • 02.List the 10 largest files in the current directory.
    du -ah . | sort -rh | head -10
  • 03.Search and replace text across all files containing it.
    grep -rl 'old' . | xargs sed -i 's/old/new/g'
  • 04.Count total files recursively.
    find . -type f | wc -l
  • 05.Show all users currently logged in to the system.
    who
  • 06.Make every .sh script executable recursively.
    find . -name '*.sh' -exec chmod +x {} +
  • 07.Repeat a command every 2 seconds to watch changes live.
    watch -n 2 "df -h"
  • 08.Get the current machine's external public IP.
    curl -s ifconfig.me
  • 09.List all open ports and the processes using them.
    ss -tulpn
  • 10.Show the 10 processes consuming the most memory.
    ps aux --sort=-%mem | head -10
  • 11.Show the 10 processes consuming the most CPU.
    ps aux --sort=-%cpu | head -10
  • 12.Find broken symlinks (pointing to non-existent files).
    find . -xtype l
  • 13.Delete every .DS_Store file generated by macOS.
    find . -name '.DS_Store' -delete
  • 14.Create a tar.gz backup with the date in the filename.
    tar czf backup-$(date +%F).tar.gz folder/
  • 15.Start a simple HTTP server on port 8000 to share files.
    python3 -m http.server 8000
  • 16.Format and print JSON in a readable way.
    cat data.json | python3 -m json.tool
  • 17.Follow a log live starting from the last 100 lines.
    tail -f -n 100 logfile
  • 18.Find all empty files and directories.
    find . -empty
  • 19.Count lines of code by summing all .py files in the project.
    find . -name '*.py' | xargs wc -l
  • 20.Show the size of each subdirectory sorted from smallest to largest.
    du -h --max-depth=1 | sort -h