DS DevShelfHub Projects · AI tools
Cheatsheets / Linux
Cheatsheet · Dev tooling

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.

Start hereQuick start · 6 you’ll reach for daily

Find filesfind . -name '*.py'
Tail logsjournalctl -u svc -f
Tophtop / btop / top
Portsss -tulpen
Edit + sudosudoedit /etc/…
Diskdf -h / du -sh */

scope · distrosVersions

Targets: kernel ≥ 6.x bash 5+ systemd 252+ (Debian 12 / Ubuntu 24.04 / RHEL 9)

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=autoLong listing, sizes, dotfiles.
cd - / pushd / popdToggle previous dir / dir stack.
tree -L 2Tree view, capped depth.
cp -a src dstArchive copy: preserves perms, times, symlinks.
mv old newSame-filesystem rename is atomic.
rm -ri dirRecursive + interactive. Less foot-gun than -rf.
install -m 0644 src /etc/x.confCopy + set mode in one shot.
ln -s target linkSymlink. Use absolute paths for links that move.
readlink -f pathResolve all symlinks.
file fooIdentify by content (not extension).
stat fooDetailed metadata (inode, perms, times).
mktemp / mktemp -dSafe temp files / dirs.
find . -name '*.py' -type f -mtime -7Files modified in last 7 days.
find . -type f -deleteDelete every match. Read carefully before running.
fdfind / fd (modern)Faster, friendlier find.
rg / ripgrepPreferred 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.tgzCreate / extract.
zstd -T0 / xz / gzip / pigzCompression: zstd is the modern default.

users, groups, modesPermissions

chmod 644 file / chmod u+x scriptOctal or symbolic.
chmod -R go-rwx dirStrip group + other perms recursively.
chown -R user:group pathChange owner + group.
umask 022Default permission mask. 077 for tighter dotfiles.
setfacl -m u:bob:rx filePOSIX ACL beyond owner/group/other.
getfacl fileInspect ACLs.
chattr +i file / lsattrImmutable flag — even root can’t write until cleared.
sudo -u app cmd / sudo -iRun as another user / interactive login.
sudoedit /etc/filePreferred over sudo vim: edits a temp copy.
id / groups / whoamiWho am I + which groups.
passwd / passwd -l userChange / lock a password.
useradd / userdel / usermod -aG group userManage accounts.

inspect & signalProcesses

ps -ef / ps -eo pid,user,%cpu,%mem,cmdSnapshot. Custom columns with -o.
ps aux --sort=-%mem | headTop memory users.
top / htop / btopInteractive top. htop / btop are friendlier.
pgrep -af nginx / pkill -f nginxFind / 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.
disownDetach the current backgrounded job.
strace -p pid / -f cmdTrace syscalls. -f follows forks.
lsof -p pid / lsof -i :8080Open files / sockets.
timeout 30 cmdKill after N seconds.
nice -n 10 cmd / ionice -c 3 cmdLower CPU / IO priority.

ip · ss · dnsNetworking

ip a / ip addr showPreferred over ifconfig.
ip r / ip route showRouting table.
ip -s linkInterface stats.
ss -tulpenListening sockets + processes.
ss -sConnection 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 TXTDNS lookup. Force resolver with @.
drill / kdigModern dig alternatives.
getent hosts fooUse nsswitch — respects /etc/hosts too.
traceroute / mtrPath tracing. mtr is interactive + better.
tcpdump -ni any port 443Packet capture. -w out.pcap for Wireshark.
nft list ruleset / iptables -Lnftables (modern) / iptables (legacy).
ufw / firewalldFriendlier firewall front-ends.
ssh -L 8080:db:5432 hostLocal port forward through ssh.

grep · sed · awkText processing

grep -EnHr 'pat' .Extended regex, line numbers, recursive.
grep -v / -i / -w / -l / -cInvert / icase / word / filenames / counts.
grep -A 3 -B 1 patAfter / before context lines.
rg pat / rg -t py patripgrep: fast, gitignore-aware. -t filters by type.
sed -i'.bak' -E 's/old/new/g' fileIn-place edit with backup. -E for ERE.
awk -F',' '{print $2, $5}' data.csvField-aware printing.
awk 'NR==1 || $3 > 100' data.csvKeep header + threshold filter.
cut -d: -f1 /etc/passwdColumn extraction.
sort -k2 -n / sort -u / sort -hSort by field, unique, human-readable sizes.
uniq -c / uniq -dCount / dup-only (requires sorted input).
tr -d / tr a-z A-ZDelete / translate characters.
column -t -s','Pretty-print CSV-like data.
jq '.[] | select(.x > 0)'JSON query / transform.
yq / daselSame 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 / reloadLifecycle.
systemctl enable --now unitEnable + start in one shot.
systemctl list-units --type=service --state=failedFind failed services.
systemctl edit --full unitEdit the unit file (or override snippet).
systemctl daemon-reloadRe-read units after edits.
journalctl -u unit -f / -e / --since "1 hour ago"Logs by unit, tailed / latest / time-range.
journalctl -p errFilter by priority.
journalctl --disk-usage / --vacuum-size=500MInspect / shrink journal.
systemd-analyze blame / critical-chainBoot performance.
systemctl mask unitDisable hard — can’t be re-enabled accidentally.
timers: ListTimer + matching .serviceModern cron replacement.
loginctl / hostnamectl / timedatectlSessions / hostname / clock.
bash
# /etc/systemd/system/my-api.service
[Unit]
Description=My API
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=app
Group=app
WorkingDirectory=/srv/my-api
EnvironmentFile=/etc/my-api.env
ExecStart=/usr/bin/python -m my_api
Restart=on-failure
RestartSec=5

# Hardening
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
ReadWritePaths=/var/lib/my-api
CapabilityBoundingSet=
AmbientCapabilities=

# Resource limits
LimitNOFILE=65536
MemoryMax=512M
CPUQuota=200%

[Install]
WantedBy=multi-user.target

# Lifecycle
systemctl daemon-reload
systemctl enable --now my-api
systemctl status my-api
journalctl -u my-api -f --since "10 min ago"

apt / dnf / pacmanPackage management

apt update / apt full-upgradeSync index + upgrade everything.
apt install pkg / apt remove pkg / apt purge pkgInstall / remove / remove + config.
apt show pkg / apt search termMetadata / search.
apt-mark hold pkgPin a package; updates skip it.
dpkg -l / dpkg -L pkg / dpkg -S /pathList / files-of / which-pkg-owns.
dnf install / dnf upgrade / dnf removeRHEL / Fedora.
rpm -qa / rpm -qf /pathRPM low-level queries.
pacman -Syu / -S pkg / -R pkgArch.
flatpak / snap installSandboxed app installs.
brew on macOS / linuxUserland packages; consistent across both.

filesystems & volumesDisk

df -hP / -iSpace / inodes by filesystem.
du -sh path / du -sh */Recursive sum / per-subdir.
ncdu / dustInteractive disk-usage explorers.
lsblk -f / blkidBlock devices + filesystems.
mount / umount / findmntMount table operations.
/etc/fstabPersistent mounts. findmnt --verify to lint.
mkfs.ext4 / mkfs.xfs / mkswapCreate filesystems.
fdisk / parted / sgdiskPartition tables.
lvs / vgs / pvs / lvextendLVM views + grow logical volumes.
smartctl -a /dev/sdaSMART health + wear data.
iotop / iostat -xz 1Per-process / per-device IO load.
fstrim -avTrim SSDs.

stdin · stdout · stderrPipes & redirection

cmd > out / >> outStdout overwrite / append.
cmd 2> err / 2>&1Stderr redirect / merge into stdout.
cmd &> both / cmd > out 2>&1Capture both streams.
cmd >/dev/null 2>&1Silence everything.
a | b | cPipeline. Right-to-left is fine to read; left-to-right runs concurrently.
a | tee log | bBranch the stream to a file mid-pipeline.
cmd <<EOF … EOFHeredoc. <<-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 bashPortable shebang.
set -euo pipefailPreferred 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 TERMRun a function on signal / exit.
for x in "${arr[@]}"; do … doneQuote the expansion or whitespace breaks.
while IFS= read -r line; do … done < fileRead line-by-line safely.
shellcheck script.shLinter. Run before shipping.
bashdb / bash -xDebugger / 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.

Go deeperSee also

Linux FAQ

How do I find files in Linux?

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.