Linux Command Cheatsheet: Files, Processes, Networking and systemd
By DevShelfHub
The Linux command line is the foundational interface for every developer and DevOps engineer: it runs on every server, in every container, and in every CI pipeline. This cheatsheet covers the commands you reach for daily — file and directory operations, process management, permissions, networking diagnostics, text processing with grep/awk/sed, systemd service control, package management, and disk usage — across both Debian/Ubuntu and RHEL/Fedora families.
134 items
◷ 9 min
Shell
Processes
Systemd
The Linux shell is the foundational interface for software development, system administration, and DevOps work. Whether you are SSHing into a production server, writing a CI pipeline, debugging a container, or automating a build, you are typing shell commands. Most modern infrastructure runs Linux — from AWS EC2 instances and Kubernetes pods to GitHub Actions runners and Raspberry Pis — so fluency with the command line pays dividends regardless of your primary programming language or stack.
Linux shell knowledge falls into a few conceptual clusters. File operations (find, cp, mv, ln, chmod, chown) cover 80% of daily file-system work. Text processing (grep, awk, sed, sort, uniq, cut, tr) is the Unix philosophy of composing small tools with pipes — one grep piped into awk piped into sort is often faster to write and run than a Python script. Process management (ps, top, kill, bg/fg, nohup) keeps you in control of what is running. Networking (curl, wget, ss, netstat, dig, traceroute, nc) lets you diagnose connectivity and make HTTP requests without leaving the terminal.
Modern Linux systems use systemd for service management: systemctl start/stop/enable/status and journalctl -u service -f for logs are the two commands you reach for most. Package management differs by distribution family: apt on Debian/Ubuntu, dnf or yum on RHEL/Fedora. This cheatsheet covers all of these clusters with concise command tables, common flag patterns, and gotchas that catch engineers new to each area.
Rows lean Debian / Ubuntu syntax (apt) with RHEL equivalents
(dnf) called out. ss
has replaced netstat;
ip has replaced
ifconfig /
route; journalctl
has displaced free-form /var/log on systemd boxes.
navigate & manipulateFiles & directories
ls -lah --color=auto
Long listing, sizes, dotfiles.
cd - / pushd / popd
Toggle previous dir / dir stack.
tree -L 2
Tree view, capped depth.
cp -a src dst
Archive copy: preserves perms, times, symlinks.
mv old new
Same-filesystem rename is atomic.
rm -ri dir
Recursive + interactive. Less foot-gun than -rf.
install -m 0644 src /etc/x.conf
Copy + set mode in one shot.
ln -s target link
Symlink. Use absolute paths for links that move.
readlink -f path
Resolve all symlinks.
file foo
Identify by content (not extension).
stat foo
Detailed metadata (inode, perms, times).
mktemp / mktemp -d
Safe temp files / dirs.
find . -name '*.py' -type f -mtime -7
Files modified in last 7 days.
find . -type f -delete
Delete every match. Read carefully before running.
fdfind / fd (modern)
Faster, friendlier find.
rg / ripgrep
Preferred over grep -r: faster, respects gitignore.
rsync -avz --delete src/ host:dst/
Idempotent sync. Trailing slashes matter.
tar czf out.tgz dir / tar xzf in.tgz
Create / extract.
zstd -T0 / xz / gzip / pigz
Compression: zstd is the modern default.
users, groups, modesPermissions
chmod 644 file / chmod u+x script
Octal or symbolic.
chmod -R go-rwx dir
Strip group + other perms recursively.
chown -R user:group path
Change owner + group.
umask 022
Default permission mask. 077 for tighter dotfiles.
setfacl -m u:bob:rx file
POSIX ACL beyond owner/group/other.
getfacl file
Inspect ACLs.
chattr +i file / lsattr
Immutable flag — even root can’t write until cleared.
sudo -u app cmd / sudo -i
Run as another user / interactive login.
sudoedit /etc/file
Preferred over sudo vim: edits a temp copy.
id / groups / whoami
Who am I + which groups.
passwd / passwd -l user
Change / lock a password.
useradd / userdel / usermod -aG group user
Manage accounts.
inspect & signalProcesses
ps -ef / ps -eo pid,user,%cpu,%mem,cmd
Snapshot. Custom columns with -o.
ps aux --sort=-%mem | head
Top memory users.
top / htop / btop
Interactive top. htop / btop are friendlier.
pgrep -af nginx / pkill -f nginx
Find / kill by command pattern.
kill -TERM pid / -HUP / -USR1 / -KILL (9)
Signals. -9 is the last resort.
nohup cmd >/tmp/out &
Detach from terminal. Survives logout.
disown
Detach the current backgrounded job.
strace -p pid / -f cmd
Trace syscalls. -f follows forks.
lsof -p pid / lsof -i :8080
Open files / sockets.
timeout 30 cmd
Kill after N seconds.
nice -n 10 cmd / ionice -c 3 cmd
Lower CPU / IO priority.
ip · ss · dnsNetworking
ip a / ip addr show
Preferred over ifconfig.
ip r / ip route show
Routing table.
ip -s link
Interface stats.
ss -tulpen
Listening sockets + processes.
ss -s
Connection summary.
curl -sSLv https://…
Verbose request. -w for timing breakdown.
curl -w "@curl-format.txt"
Custom timings: DNS, connect, TTFB, total.
dig +short host / dig @1.1.1.1 host TXT
DNS lookup. Force resolver with @.
drill / kdig
Modern dig alternatives.
getent hosts foo
Use nsswitch — respects /etc/hosts too.
traceroute / mtr
Path tracing. mtr is interactive + better.
tcpdump -ni any port 443
Packet capture. -w out.pcap for Wireshark.
nft list ruleset / iptables -L
nftables (modern) / iptables (legacy).
ufw / firewalld
Friendlier firewall front-ends.
ssh -L 8080:db:5432 host
Local port forward through ssh.
grep · sed · awkText processing
grep -EnHr 'pat' .
Extended regex, line numbers, recursive.
grep -v / -i / -w / -l / -c
Invert / icase / word / filenames / counts.
grep -A 3 -B 1 pat
After / before context lines.
rg pat / rg -t py pat
ripgrep: fast, gitignore-aware. -t filters by type.
sed -i'.bak' -E 's/old/new/g' file
In-place edit with backup. -E for ERE.
awk -F',' '{print $2, $5}' data.csv
Field-aware printing.
awk 'NR==1 || $3 > 100' data.csv
Keep header + threshold filter.
cut -d: -f1 /etc/passwd
Column extraction.
sort -k2 -n / sort -u / sort -h
Sort by field, unique, human-readable sizes.
uniq -c / uniq -d
Count / dup-only (requires sorted input).
tr -d / tr a-z A-Z
Delete / translate characters.
column -t -s','
Pretty-print CSV-like data.
jq '.[] | select(.x > 0)'
JSON query / transform.
yq / dasel
Same idea for YAML / TOML / XML.
xargs -r -n1 -I{} cmd {}
Argument plumbing. -r skips empty input.
bash
# Build pipelines: each tool does one thing, glue them together.
# Top 10 IPs in an access log
awk '{print $1}' access.log | sort | uniq -c | sort -nr | head -10
# Disk usage of subdirectories, biggest first
du -sh */ 2>/dev/null | sort -hr | head
# Find huge files (>100 MB), oldest first
find / -type f -size +100M -printf '%T@ %p %s\n' 2>/dev/null \
| sort -n | head
# Find listening TCP ports + owning processes (no root needed for own pids)
ss -tulpen | column -t | sort -k5
# Stream from a remote log via ssh, locally grep
ssh prod 'sudo journalctl -u api -f' | grep -E 'ERROR|WARN'
# Compose with xargs to handle huge lists
git ls-files '*.py' | xargs grep -l 'TODO'
# Substitute output as files via process substitution
diff <(sort a.txt) <(sort b.txt)
services + journalsSystemd
systemctl status unit / start / stop / restart / reload
Pipeline. Right-to-left is fine to read; left-to-right runs concurrently.
a | tee log | b
Branch the stream to a file mid-pipeline.
cmd <<EOF … EOF
Heredoc. <<-EOF strips leading tabs.
cmd <<<"string"
Here-string. Feed a literal to stdin.
<(cmd) / >(cmd)
Process substitution. Substitute a command as a file.
|| / &&
Short-circuit on prev failure / success.
$(cmd) vs `cmd`
Prefer $(): nestable, safer.
bash, with safetyShell scripting
#!/usr/bin/env bash
Portable shebang.
set -euo pipefail
Preferred Exit on error, unset var, pipeline fail.
IFS=$'\n\t'
Safer word splitting.
${var:-default} / ${var:?msg}
Default value / fail with message.
${#var} / ${var//pat/repl}
Length / pattern substitution.
[[ str == glob ]] / [[ str =~ regex ]]
Conditional expressions. Quote nothing on the LHS.
trap cleanup EXIT INT TERM
Run a function on signal / exit.
for x in "${arr[@]}"; do … done
Quote the expansion or whitespace breaks.
while IFS= read -r line; do … done < file
Read line-by-line safely.
shellcheck script.sh
Linter. Run before shipping.
bashdb / bash -x
Debugger / trace every line.
bash
#!/usr/bin/env bash
# Strict mode — every script you write
set -euo pipefail
IFS=$'\n\t'
# Trap cleanup on exit
tmp=$(mktemp -d)
cleanup() { rm -rf "$tmp"; }
trap cleanup EXIT INT TERM
# Args + defaults
host=${1:?usage: $0 [path]}
path=${2:-/var/log}
# Functions
log() { printf '%(%Y-%m-%dT%H:%M:%S%z)T %s\n' -1 "$*" >&2; }
# Branching
if [[ $host == *.local ]]; then
log "Local domain detected"
elif [[ $host =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
log "IP literal"
fi
# Loops
for f in "$path"/*.log; do
[[ -f $f ]] || continue
wc -l "$f"
done
# Capture command output safely
hostname=$(uname -n)
echo "running on $hostname"
# Arrays
declare -a hosts=(api1.example.com api2.example.com)
for h in "${hosts[@]}"; do
ping -c 1 "$h" >/dev/null && log "$h up"
done
disk · service · logsEnd-to-end · Host health check
Disk warning, top processes, service liveness, recent error spike, FD count — the script you wire into
your monitoring agent when nothing fancier is installed.
bash
#!/usr/bin/env bash
# health-check.sh — disk + processes + service + log spike check, in one script.
set -euo pipefail
WARN=80 # percent
SERVICE=my-api
# 1. Disk on / and /var
df -hP / /var | awk -v w="$WARN" '
NR>1 {
pct=$5; gsub("%","",pct);
if (pct+0 >= w) printf("DISK %s on %s\n", $5, $6);
}'
# 2. Top processes by RSS
ps -eo pid,user,rss,cmd --sort=-rss | head -6
# 3. Service liveness via systemd
if systemctl is-active --quiet "$SERVICE"; then
echo "$SERVICE: active"
else
echo "$SERVICE: DOWN"
journalctl -u "$SERVICE" --since "5 min ago" | tail
fi
# 4. Error spike in last 5 min
since=$(date -d '5 min ago' +'%Y-%m-%d %H:%M:%S')
err_count=$(journalctl -u "$SERVICE" --since "$since" \
| grep -cE 'ERROR|FATAL' || true)
echo "errors_last_5min=$err_count"
[[ $err_count -gt 50 ]] && echo "WARN: error spike"
# 5. Open file descriptors
echo "fd_in_use=$(lsof -u app 2>/dev/null | wc -l)"
Best practiceGood to know
Default to set -euo pipefail in every script.
Catches missing vars, command failures, and broken pipelines without you noticing — the most common
class of “works on my laptop” bash bugs.
Prefer journalctl -u over tail /var/log.
Structured filtering, per-unit scoping, time-ranges — pretty much everything you used to grep for is a
flag away.
Use sudoedit, not sudo $EDITOR.
sudoedit copies the file, drops privileges to edit, then promotes back. sudo vim
runs the whole editor (and plugins, and macros) as root.
Common trapsWatch out for
Unquoted globs eat your weekend.rm $foo/* where $foo is empty becomes
rm /*. Quote variables, always ("$foo") —
and prefer rm -i when interactive.
Right-hand side of [[ =~ ]] must be unquoted.[[ "$x" =~ "^foo" ]] matches the literal string
^foo. Drop the quotes: [[ $x =~ ^foo ]].
Symlink loops crash naive recursion.find -L follows symlinks — great until two dirs link to each other.
Prefer find -P (default) unless you really need to traverse.
Use find . -name '*.log' to search by filename pattern, find . -mtime -1 to find files modified in the last day, and find . -size +100M to find large files. For fast indexed search, install mlocate and use locate filename. Use grep -r pattern dir/ to search file contents recursively, or ripgrep (rg) for a significantly faster alternative.
How do Linux file permissions work?
Linux permissions are set per file for three principals: owner, group, and others. Each principal has read (r=4), write (w=2), and execute (x=1) bits. chmod 755 sets owner rwx, group r-x, others r-x. Use chmod u+x file to add execute permission for the owner only. chown user:group file changes ownership.
How do I manage processes in Linux?
List running processes with ps aux or the interactive top (or htop). Kill a process by PID with kill PID (sends SIGTERM) or kill -9 PID (SIGKILL, immediate). Find a process by name with pgrep name or pkill name. Use nohup command & to run a process in the background that survives terminal close, or use a process manager like systemd or supervisor.
What is systemd in Linux?
systemd is the init system and service manager on most modern Linux distributions (Debian, Ubuntu, Fedora, Arch). It starts services in parallel at boot, manages their lifecycle with systemctl start/stop/restart/enable, and collects logs in a structured journal accessible via journalctl. Unit files in /etc/systemd/system/ define services, timers, and mounts.
How do I monitor disk usage in Linux?
df -h shows filesystem-level disk usage in human-readable form. du -sh dir/* lists the size of each subdirectory to find what is consuming space. lsblk lists all block devices and their mount points. ncdu is an interactive terminal UI for navigating disk usage that makes it easy to drill into large directories and delete files safely.