Linux Cheat Sheet
Terminal commands, bash, pipes and one-liners
Navigation
Lists the contents of a directory with permissions, size and date.
ls -la /var/log
Changes the current directory. Without arguments goes to home.
cd /etc/nginx cd ~ cd - cd ..
Prints the full path of the current directory.
pwd
Shows the directory tree in visual form.
tree -L 2 ~/projects
Identifies the type of a file (text, binary, image, script, etc).
file image.png file -i script.sh
Shows detailed metadata of a file (size, inode, dates, permissions).
stat file.txt stat -c "%n %s %y" file.txt
Files
Creates an empty file or updates the modification timestamp.
touch newfile.txt touch -t 202601011200 file.txt
Creates a directory. With -p creates the full parent path if missing.
mkdir -p projects/app/src mkdir -m 700 secret
Removes an empty directory.
rmdir empty_dir rmdir -p a/b/c
Removes files or directories. With -rf removes recursively without confirmation (dangerous).
rm file.txt rm -rf node_modules
Copies files or directories.
cp file.txt backup.txt cp -r src/ dest/
Moves or renames files and directories.
mv old.txt new.txt mv *.log archive/
Creates links: -s for symbolic, no flag for hard link.
ln -s /usr/local/bin/node ~/node ln file hardlink
Prints the contents of one or more files to stdout.
cat file.txt cat -n script.sh
Pages through files with navigation. Search with /. +F follows like tail -f.
less /var/log/syslog less +F app.log
Shows the first N lines of a file (default: 10).
head -n 20 file.txt head -c 1024 binary
Shows the last N lines. -f follows the file as it grows.
tail -n 50 access.log tail -f /var/log/syslog
Counts lines (-l), words (-w), bytes (-c) or characters (-m).
wc -l file.txt wc *.md
Permissions
Changes file and directory permissions (rwx).
chmod 755 script.sh chmod +x deploy.sh chmod -R 644 docs/
Changes the owner and/or group of files.
chown user file.txt chown -R www-data:www-data /var/www
Runs a command as another user (root by default).
sudo apt update sudo -u postgres psql sudo -i
Switches to another user. - loads that user's environment.
su - postgres su -c 'whoami' root
Creates (useradd) or deletes (userdel) user accounts.
sudo useradd -m -s /bin/bash john sudo userdel -r john
Sets or changes a user's password.
passwd sudo passwd john
Shows the current user (whoami) or all logged-in users (who).
whoami who who -a
Shows the current user's UID, GID and group memberships.
id id -nG groups
Processes
Lists processes. aux shows all processes with detail.
ps aux ps -ef
Shows processes in real time, sorted by CPU/memory usage.
top top -u www-data top -p 1234
Sends a signal to a process by PID. -9 forces termination (SIGKILL).
kill 1234 kill -9 1234 kill -HUP $(pidof nginx)
Kills processes by name (killall) or pattern (pkill).
killall firefox pkill -9 -f node pkill -u john
Manages shell jobs: jobs lists them, fg brings to foreground, bg resumes in background.
jobs fg %1 bg %2 # Ctrl+Z to suspend the foreground job
Runs a command that keeps running after closing the terminal.
nohup ./long-task.sh > out.log 2>&1 & nohup python script.py &
Starts a process with adjusted priority (nice) or changes the priority (renice).
nice -n 19 ./heavy.sh renice -n 5 -p 1234
Appending & at the end of a command runs it in background, freeing the terminal.
./server.sh & long-task & disown %1
Network
Tests connectivity by sending ICMP packets. -c limits the count.
ping google.com ping -c 4 8.8.8.8
Makes HTTP/HTTPS requests and downloads files. Supports GET, POST, headers, authentication.
curl https://api.github.com
curl -X POST -H "Content-Type: application/json" -d '{"a":1}' url
curl -O https://example.com/file.zipDownloads files via HTTP/FTP. Supports resume with -c and recursive mirroring.
wget https://example.com/file.zip wget -c <url> wget -r -np https://site/docs/
Connects to a remote server via Secure Shell. -L creates tunnels for local ports.
ssh user@host ssh -p 2222 -i ~/.ssh/id_ed25519 user@host ssh -L 8080:localhost:80 user@host
Copies files between machines via SSH.
scp file.txt user@host:/tmp/ scp -r dir/ user@host:/var/www/ scp user@host:/etc/conf .
Synchronises files and directories efficiently. -avz is the most common combination.
rsync -avz src/ user@host:/dest/ rsync -av --delete --exclude='.git' a/ b/
Shows listening ports and active connections. -tulpn is the typical usage.
ss -tulpn ss -t state established
Queries DNS. dig is more detailed, nslookup simpler, host more concise.
dig google.com dig +short MX gmail.com nslookup example.com 8.8.8.8
Compression
Packs and compresses directories. -czf creates with gzip, -xzf extracts.
tar -czvf archive.tar.gz folder/ tar -xzvf archive.tar.gz tar -tf archive.tar.gz
Zip compression. unzip -l lists contents without extracting.
zip -r out.zip folder/ unzip archive.zip unzip -l archive.zip
Compresses/decompresses individual files with gzip. -k keeps the original.
gzip file.txt gzip -d file.txt.gz gzip -k file.txt
Bzip2 compression, slower but with better ratio than gzip.
bzip2 file.txt bunzip2 file.txt.bz2
Xz compression, even better ratio. -T0 uses all cores.
xz file.txt unxz file.txt.xz xz -T0 file
7z format, high compression ratio. Supports password and split archives.
7z a out.7z folder/ 7z x archive.7z 7z a -p out.7z secret.txt
Search
Searches files by name, type, size, age, and runs actions with -exec.
find . -name "*.log" find / -type f -size +100M find . -mtime -7 find . -name "*.tmp" -delete
Searches patterns in files. -r recursive, -i case-insensitive, -E enables regex.
grep -rn "TODO" src/ grep -i error log grep -E "warn|error" file
Processes text column by column. Full language for parsing structured files.
awk '{print $1}' file.txt
awk -F',' '{print $2}' csv
awk '/error/ {count++} END {print count}' logEdits text streams. -i edits files in place, mostly used for substitutions.
sed 's/old/new/g' file sed -i 's/old/new/g' file sed -n '10,20p' file
Finds binaries and files: locate (cache), which (in PATH), whereis (binary, source, manual).
locate nginx.conf which python3 whereis bash
Redirection
Redirects stdout to a file, overwriting existing content.
echo hello > out.txt ls -la > files.txt
Redirects stdout to a file, appending to existing content.
echo "line" >> log.txt date >> events.log
Connects stdout of one command to stdin of the next, chaining processes.
ls -la | grep .conf cat file | sort | uniq
Redirects stderr (fd 2). 2>&1 merges stderr into stdout. &> does both in bash.
cmd 2> errors.log cmd > out.log 2>&1 cmd &> all.log
Reads from stdin and writes to a file AND to stdout. -a appends instead of overwriting.
ls | tee files.txt echo 'data' | sudo tee /etc/conf make | tee -a build.log
Builds commands from stdin. Indispensable for combining find or grep with other commands.
find . -name "*.log" | xargs rm
echo "a b c" | xargs -n 1
ls *.txt | xargs -I {} cp {} backup/Environment
Sets environment variables that are inherited by child processes.
export PATH="$PATH:/opt/bin" export API_KEY="abc123" export -p
Lists all active environment variables. printenv can show a specific one.
env printenv PATH env VAR=value command
Creates command shortcuts. Set in ~/.bashrc or ~/.zshrc to make permanent.
alias ll='ls -la' alias gs='git status' unalias ll
Prints text or variables to stdout. -e enables escapes like \n and \t.
echo "Hello $USER" echo -e "line1\nline2" echo $PATH
Loads a script in the current shell (not a subshell). Useful for .bashrc and venv.
source ~/.bashrc . ~/.zshrc source venv/bin/activate
Shows command history. !! repeats the last, !N runs command N.
history history | grep ssh !! !42
Packages
Debian/Ubuntu package manager. apt is more modern and friendly than apt-get.
sudo apt update && sudo apt upgrade sudo apt install nginx sudo apt remove --purge package apt search keyword
Red Hat/Fedora/CentOS package manager. dnf is the modern successor of yum.
sudo dnf install nginx sudo yum update dnf search keyword
Package manager for macOS and Linux with community-maintained formulae.
brew install wget brew update && brew upgrade brew list brew search node
Arch Linux package manager. -Syu updates everything, -S installs, -R removes.
sudo pacman -S nginx sudo pacman -Syu pacman -Ss keyword
Universal sandboxed packages. Install on any modern distribution.
sudo snap install code flatpak install flathub org.gimp.GIMP snap list
SSH
Generates SSH key pairs. ed25519 is the current recommendation (faster and safer than RSA).
ssh-keygen -t ed25519 -C "john.doe@example.com" ssh-keygen -t rsa -b 4096
Copies the public key to the remote server's ~/.ssh/authorized_keys.
ssh-copy-id user@host ssh-copy-id -i ~/.ssh/id_ed25519.pub -p 2222 user@host
SSH agent keeps decrypted keys in memory so passphrase isn't asked on every connection.
eval "$(ssh-agent -s)" ssh-add ~/.ssh/id_ed25519 ssh-add -l
Interactive SFTP client to transfer files via SSH.
sftp user@host put file.txt get remote.zip ls bye
Per-host SSH config file. Allows alias, identity, port and jump host configuration.
Host myserver HostName 1.2.3.4 User john Port 2222 IdentityFile ~/.ssh/id_ed25519
Disk
Shows used and available space per filesystem. -h in human-readable format.
df -h df -h / df -i
Shows space used by files and directories. -sh summary in human-readable format.
du -sh * du -h --max-depth=1 du -ah . | sort -rh | head -20
Mounts a filesystem at a mount point. umount unmounts.
mount sudo mount /dev/sdb1 /mnt/data sudo umount /mnt/data
Lists disks and partitions in tree (lsblk) or table (fdisk) format.
lsblk lsblk -f sudo fdisk -l
Shows total, used, free and cached RAM. -h in human-readable format.
free -h free -m free -h -s 2
Monitoring
Improved version of top with colors, scroll, and kills processes with F9.
htop htop -u www-data htop -p 1234,5678
Virtual memory, CPU and IO statistics. Useful for diagnosing bottlenecks.
vmstat vmstat 2 5
Disk IO statistics. Identifies saturated disks.
iostat iostat -xz 2
Shows kernel messages. Useful for diagnosing hardware or driver problems.
sudo dmesg | tail sudo dmesg -T sudo dmesg -w
Controls systemd services: start, stop, status, enable on boot.
sudo systemctl start nginx sudo systemctl status sshd sudo systemctl enable docker
systemd logs. -f follows live, -u filters by service, --since by time.
journalctl -u nginx journalctl -f journalctl --since "1 hour ago" journalctl -p err
uptime shows how long the system has been running and the load average. w lists logged-in users and what they are doing.
uptime w
Advanced
Repeats a command periodically. -d highlights changes between runs.
watch -n 2 "df -h" watch -d "ls -l" watch "ps aux | grep node"
Creates persistent terminal sessions that survive logouts. Classic version.
screen -S work screen -r work screen -ls # Ctrl+A D to detach
Modern terminal multiplexer: multiple windows, panes and persistent sessions.
tmux new -s work tmux attach -t work tmux ls # Ctrl+B D to detach
Periodic task scheduler. crontab -e edits the current user's jobs.
crontab -e crontab -l 0 3 * * * /script.sh # daily at 3am */15 * * * * /poll.sh # every 15 minutes
Schedules a command to run only once at a future time.
echo "/script.sh" | at now + 1 hour at 14:30 tomorrow atq at -r 5
Reference
Every process has three default streams identified by file descriptors. Understanding these streams is the key to combining commands with pipes and redirections.
stdinfd 0Standard 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 1Standard output. By default goes to the terminal. Redirected with > (overwrite) or >> (append).
stderrfd 2Errors and warnings. A separate stream so errors don't mix with normal output. Redirected with 2>.
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
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.
u— file ownerg— file groupo— everyone elsea— all (u+g+o)
r= 4 — readw= 2 — writex= 1 — execute (or enter directory)
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
The shell can run multiple jobs at once. Only the foreground job uses the terminal; background jobs keep running while you type other commands.
Job using the terminal. Receives keyboard input and shows output. Blocks the prompt until it finishes.
Job running in parallel, not occupying the terminal. Frees the prompt for other commands. Stop it with kill or by bringing it to fg.
./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
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