Linux · Cheat sheet
Linux command cheat sheet
Linux command cheat sheet for DevOps and security: files, permissions, processes, networking, systemd, and shell tools.
Rows marked Destructive State operation Caution Exposes secrets can remove data, change authoritative state, affect a running system, or print secrets. Read the note before running them against anything that matters.
Navigation & files
Beginnerls -lah- Long listing with human sizes and hidden files.Example output
drwxr-xr-x 4 root root 4.0K Jun 12 09:14 . -rw-r--r-- 1 app app 1.2K Jun 12 09:10 app.conf
pwd- Print the current directory path.
cd -- Jump back to the previous directory.
cp -r src/ dst/- Copy a directory recursively.
mv old new- Move or rename.
rm -rf dir/Destructive- Delete recursively and force (no prompt).Destructive: Irreversible; a typo or empty variable in the path deletes the wrong tree.
mkdir -p a/b/c- Create nested directories in one go.
ln -s /opt/app/bin app- Create a symbolic link.
stat file- Size, permissions, and access/modify times.
file /bin/ls- Identify a file’s type.Example output
/bin/ls: ELF 64-bit LSB pie executable, x86-64
Viewing & editing text
Beginnercat file- Print a whole file.
less file- Page through a file (q to quit, / to search).
head -n 20 file- First 20 lines.
tail -f /var/log/syslog- Follow a log as it grows (journald-only hosts: journalctl -f).
wc -l file- Count lines.Example output
428 file
nano file- Beginner-friendly editor (Ctrl-O save, Ctrl-X exit).
vim file- Modal editor — i insert, Esc, :wq save+quit.
echo "text" > fileCaution- Overwrite a file with text.Caution: > truncates the file first; use >> to append.
echo "more" >> file- Append to a file.
Search & filter
Beginnergrep -rni "error" /var/log- Recursive, case-insensitive, with line numbers.Example output
/var/log/app.log:42: ERROR failed to connect
find . -name "*.log" -mtime -1- Files matching a pattern, changed in last day.
find / -size +100M 2>/dev/null- Files larger than 100 MB.
which python3- Path of a command on $PATH.
sort file | uniq -c | sort -rn- Count and rank duplicate lines.
cut -d: -f1 /etc/passwd- First colon-delimited field (usernames).
ps aux | grep "[n]ginx"- Find a process without matching grep itself.
command | xargs -n1 <cmd>- Turn stdin lines into command arguments.
Permissions & ownership
Intermediatechmod 640 file- Octal: rw- owner, r-- group, --- others.
chmod u+x,go-w script.sh- Symbolic: add owner-exec, remove group/other-write.
chown user:group file- Change owner and group.
umask 027- Default new files to no world access.
ls -l file- Read the permission string.Example output
-rw-r----- 1 app dev 1.2K app.conf (owner rw, group r)
setfacl -m u:deploy:rx /opt/app- Grant one user extra access via ACL.
getfacl /opt/app- Show ACL entries beyond the basic bits.
find / -perm -4000 2>/dev/null- Locate SUID binaries (privilege audit).
chattr +i /etc/resolv.conf- Make a file immutable (root must run chattr -i before editing).
Processes & jobs
Intermediateps aux --sort=-%cpu | head- Top CPU consumers right now.
top- Live process table (P=sort by CPU, M=by mem).
kill -TERM <pid>- Ask a process to shut down cleanly.
kill -9 <pid>Caution- Force-kill (uncatchable SIGKILL).Caution: No graceful shutdown: skips cleanup and can leave locks or half-written files.
pkill -f "python app.py"Caution- Kill by command-line pattern.Caution: Matches full command lines and can hit other processes; preview with pgrep -af.
pgrep -a nginx- List PIDs (and args) matching a name.
nohup ./job.sh &- Run detached, immune to hangup.
jobs / fg %1 / bg %1- Manage background jobs in the shell.
nice -n 10 ./batch.sh- Start a process at lower priority.
watch -n2 "ss -s"- Re-run a command every 2s (-d highlights what changed).
Users, groups & sudo
Intermediateid- Your UID, GID and group memberships.Example output
uid=1000(app) gid=1000(app) groups=1000(app),27(sudo)
useradd -m -s /bin/bash deploy- Create a user with a home dir and shell.
usermod -aG docker deployCaution- Add a user to a supplementary group (docker = root-equivalent).Caution: Docker group membership is root-equivalent on the host.
passwd deploy- Set or change a password.
su - deploy- Switch to another user (login shell).
sudo -l- List what you are allowed to run via sudo.
visudo- Safely edit /etc/sudoers (syntax-checked).
w- Who is logged in and what they are running.
last- Recent login history (Debian 13 dropped it; use wtmpdb or lslogins).
Disk, storage & mounts
Intermediatedf -h- Free space per filesystem, human-readable.Example output
Filesystem Size Used Avail Use% Mounted on /dev/sda1 40G 28G 10G 74% /
du -sh *- Size of each item in the current directory.
lsblk- Block devices and their mount points as a tree.
mount /dev/sdb1 /mnt- Mount a filesystem.
findmnt /- Show the source and options for a mount.
free -h- Memory and swap usage.
ncdu /var- Interactive disk-usage explorer.
lsof | grep deleted- Find space held by deleted-but-open files.
Networking
Intermediateip addr- Interfaces and assigned addresses (short form: ip a).
ip route- The routing table (short form: ip r).
ss -tulpn- Listening TCP/UDP sockets and owning PIDs.Example output
Netid State Local Address:Port Process tcp LISTEN 0.0.0.0:22 sshd tcp LISTEN 0.0.0.0:443 nginx
curl -I https://host- Fetch just the response headers.
curl -s https://api/health | jq .- Fetch a body and pretty-print JSON.
dig +short host- Quick DNS resolution.
resolvectl status- Per-link DNS servers when systemd-resolved manages DNS.
nc -zv host 443- Test whether a TCP port is open.
ssh -i key.pem user@host- SSH with a specific key.
rsync -avz --delete src/ user@host:/dst/Destructive- Efficient mirror over SSH.Destructive: --delete removes files on the destination that are not in src/; dry-run with -n first.
nft list ruleset- Print the active nftables firewall ruleset.
Systemd & services
Intermediatesystemctl status nginx- Service state, PID, and recent logs.Example output
● nginx.service - A high performance web server Active: active (running) since Thu 09:12:04 UTC
systemctl start|stop|restart nginxCaution- Control a service now.Caution: stop/restart interrupts the service; prefer reload where the unit supports it.
systemctl enable --now nginx- Start now and on boot.
systemctl is-enabled nginx- Will it start at boot?
systemctl daemon-reload- Reload unit files after editing them.
journalctl -u nginx -f- Follow one unit’s logs live.
journalctl -p err -b- Errors since the last boot.
journalctl -k- Kernel messages for this boot (OOM kills, disk and driver errors).
systemctl list-units --failed- Show units that failed to start.
Packages & archives
Intermediateapt update && apt install -y nginx- Refresh index and install (Debian/Ubuntu).
apt list --installed- List installed packages.
dnf install -y nginx- Install (Fedora/RHEL).
rpm -qa | grep openssl- Query installed RPMs.
dpkg -l | grep ssh- Query installed .deb packages.
tar -czf out.tgz dir/- Create a gzipped archive.
tar -xzf out.tgz -C /dst- Extract into a directory.
zip -r out.zip dir/ && unzip out.zip- Create and extract a zip.
awk, sed & pipes
Advancedawk '{print $1, $NF}' file- Print the first and last field of each line.
awk -F: '$3>=1000 {print $1}' /etc/passwd- Filter by a computed condition, custom delimiter.Example output
app deploy
sed -n '10,20p' file- Print a line range.
sed -i 's/debug/info/g' app.confCaution- In-place find/replace across a file.Caution: Edits in place with no backup; the -i.bak form below keeps one.
sed -i.bak 's/old/new/' file- Same, but keep a .bak backup.
grep -Eo "[0-9]+\.[0-9]+\.[0-9]+" file- Extract only the matching text (regex).
command | tee out.log- Print to screen and write to a file.
diff -u a.txt b.txt- Unified diff between two files.
column -t -s,- Align CSV into readable columns.
Performance & tracing
Advanceduptime- Load averages over 1/5/15 min.Example output
09:20:01 up 12 days, load average: 0.42, 0.55, 0.61
vmstat 1- CPU, memory, IO and swap every second.
iostat -xz 1- Per-device disk utilization and latency.
mpstat -P ALL 1- Per-core CPU breakdown.
sar -n DEV 1- Per-interface network throughput.
strace -f -e trace=openat -p <pid>- Trace the syscalls a process makes.
lsof -i :443- What is using a given port.
tcpdump -ni eth0 port 443- Capture packets on an interface.
perf top- Live sampling of the hottest kernel/user functions.
Shell scripting
Advanced#!/usr/bin/env bash- Shebang — the interpreter for the script.
set -euo pipefail- Fail fast on most errors, unset vars, pipe failures (-e is off in if/&&/|| tests).
for f in *.log; do gzip "$f"; done- Loop over files.
if [[ -f "$f" ]]; then ...; fi- Test a condition ([[ ]] is the bash test).
name=$(hostname)- Capture command output into a variable.
echo "exit code: $?"- Exit status of the last command (0 = ok).
cmd1 && cmd2 || cmd3- cmd2 if cmd1 succeeds; cmd3 if cmd1 or cmd2 fails (not if/else).
trap 'rm -f "$tmp"' EXIT- Run cleanup when the script exits.
crontab -e- Edit scheduled jobs (min hour dom mon dow cmd).Example output
0 3 * * * /opt/backup.sh # every day at 03:00
Related
- Cheat sheetBash scripting cheat sheet
- Cheat sheetPython for DevSecOps cheat sheet
- Interview guideLinux interview questions
- CourseLinux essentials
- CourseLinux hardening
- CourseAdvanced Linux security
- Field noteSandboxing Linux services with systemd security directives
- Field noteLinux capabilities: dropping root the right way
- Field noteCentralized logging with journald and rsyslog
Primary references
Found a technical issue on this page? Report it with the tool version you used and the behavior you saw. How resources are maintained.
Go deeper
Hands-on courses for Linux