Linux · Cheat sheet

Linux command cheat sheet

Linux command cheat sheet for DevOps and security: files, permissions, processes, networking, systemd, and shell tools.

118 commands·13 sections·Updated ·By SecOpsLog

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.

Beginner
ls -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

Beginner
cat 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

Beginner
grep -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

Intermediate
chmod 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

Intermediate
ps 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

Intermediate
id
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

Intermediate
df -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

Intermediate
ip 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

Intermediate
systemctl 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

Intermediate
apt 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

Advanced
awk '{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

Advanced
uptime
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

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