Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Operations 135 min read

Linux Troubleshooting: 30 High-Frequency Commands with Diagnosis Logic & Pitfalls

This article details 30 essential Linux commands for file, permission, process, and network troubleshooting, each including purpose, command, expected output, judgment criteria, and risks, plus five real-world scenarios that demonstrate diagnostic reasoning chains.

Background: Cheat Sheets Are Not Enough

Typical Linux command cheat sheets only list commands and basic descriptions (e.g., ls lists directories, grep searches text). They answer "what is the command" but fail to address three critical questions for real troubleshooting:

How to judge the output? Example: df -h shows / at 85% usage. Is that a problem? It depends on whether Avail is tens of gigabytes (normal) or only 200 MB and dropping (emergency). Same command, opposite conclusions.

Does the command have side effects? chmod -R 777 "solves" permission issues but destroys security boundaries; kill -9 "solves" stuck processes but loses unwritten data, leaves lock files, and may corrupt databases; > app.log "solves" disk full but if the file is held open by a process, space is not actually released.

Where to go when output doesn't match expectations? ss -lntp shows port 80 listened by nginx, but curl localhost:80 times out. Next steps: check firewall, SELinux, nginx listen binding (127.0.0.1 vs 0.0.0.0), or conntrack table exhaustion. These decision branches are the real troubleshooting content.

This article organizes 30 high-frequency operations into four groups: files & disk, permissions & ownership, processes & resources, network. Each operation provides five elements: purpose, command, expected output, judgment criteria, and pitfalls/risks. Five real-world scenarios then chain them together—individual commands are easy, chaining them is troubleshooting.

Applicable Scenarios and Environment Assumptions

Covered

Single-host troubleshooting: disk full, permission denied, process hang, port unreachable, DNS anomalies.

Daily inspections: capacity, load, connection counts, anomalous processes.

Pre-change checks and post-change verification.

Not Covered

Kernel parameter tuning (sysctl details).

Container-specific behaviors (e.g., ps sees only container PID namespace, free reads host memory).

Performance profiling (perf, eBPF)—only mentions when to switch tools.

Environment Assumptions

Distributions: Ubuntu 22.04/24.04, Rocky Linux 9, Debian 12 (commands largely universal; package names and config paths may differ).

Init: systemd 249+ ( service / chkconfig are legacy compatibility).

Network tools: iproute2 ( ip, ss); netstat / ifconfig (net-tools) often not installed by default.

Firewall: nftables backend ( iptables-nft or nft); iptables commands still work but map to nft.

Shell: bash 5.x (some examples use bash 4+ syntax like mapfile, [[ ]]).

Root-required operations marked with #; non-root users get Operation not permitted.

Tool Replacements: Why New Commands Replace Old Ones

netstat -tlnp

→ ss -lntp: netstat scans entire /proc table, hangs at tens of thousands of connections; ss uses netlink, an order of magnitude faster. ifconfig → ip addr: ifconfig lacks multi-IP and policy routing support, unmaintained. route -n → ip route: same reasons. iptables -L → nft list ruleset (or iptables-nft): new kernels use nft; mixing causes "rules written but not effective". service x restart → systemctl restart x: service is a compatibility wrapper, cannot retrieve full unit state.

If ss is missing, install iproute2 rather than net-tools.

File and Disk: 8 Operations

3.1 List Directory Contents, Sorted by Time and Size

Purpose: Quickly locate recently modified files (config drift, latest logs) or find large files in a directory.

Commands:

# Detailed list, human-readable sizes, show hidden files
ls -alh

# Sort by modification time, newest first
ls -lht

# Sort by size descending (only immediate entries; directory size excludes contents)
ls -lhS

# List directories themselves, not their contents
ls -ld /var/log /data

Expected Output:

total 1.2G
-rw-r----- 1 root adm  1.1G Oct 30 09:12 syslog
drwxr-xr-x 2 root root 4.0K Oct 29 18:00 apt
-rw-r--r-- 1 root root 128M Oct 28 03:00 syslog.1

Judgment Criteria: ls -lhS shows directory size as 4.0K (directory entry size), not total content size. Using ls to find large directories is invalid; must use du (see 3.4). This pitfall recurs yearly.

Pitfall: Filenames with spaces or special characters make ls output unreliable for parsing. Never use for f in $(ls) in scripts; use glob or find -print0.

3.2 Find Large Files

Purpose: When disk is nearly full, identify the culprit.

Command:

# Find regular files >1GB on root filesystem, sort by size descending, human-readable output
find / -xdev -type f -size +1G -printf '%s	%p
' 2>/dev/null |
  sort -rn | head -20 |
  awk '{printf "%.1fG	%s
", $1/1024/1024/1024, $2}'

Expected Output:

18.4G   /var/lib/docker/overlay2/ab12.../diff/var/log/app.log
6.2G    /data/mysql/ibdata1
1.9G    /var/log/syslog.1

Judgment Criteria: -xdev prevents crossing filesystem boundaries; without it, /proc, /sys, and network mounts are scanned—slow and meaningless.

If top file is *.log, issue is log rotation; if under overlay2, container logging (Docker json-file driver doesn't rotate by default); if database file, check binlog/undo cleanup.

Empty output means no single file >1GB; space consumed by many small files—switch to du.

Pitfall: find / on multi-TB storage can run minutes to hours and saturate disk IO. In production, run on suspect directories ( /var, /data, /home) or use ionice -c3 find ... to lower IO priority.

3.3 Check Disk Usage and Inodes

Purpose: Distinguish "space full" from "inodes full"—both report No space left on device but require completely different fixes.

Commands:

# Space usage
df -hT

# Inode usage
df -i

Expected Output:

Filesystem     Type   Size  Used Avail Use% Mounted on
/dev/nvme0n1p2 ext4   234G  198G  24G  90% /
/dev/nvme1n1   xfs    1.8T  1.2T 600G  67% /data
tmpfs          tmpfs   16G     0  16G   0% /dev/shm
Filesystem      Inodes  IUsed   IFree IUse% Mounted on
/dev/nvme0n1p2  15.6M   15.6M     12  100% /
/dev/nvme1n1    1.8G    2.1M   1.8G   1% /data

Judgment Criteria: Use% high but Avail still tens of GB = not urgent; Avail below 10% and dropping = urgent.

IUse% 100% while Use% only 40% = classic inode exhaustion. Cause: hundreds of thousands of small files in a directory (session files, mail queues, cache fragments). df -h hides this; df -i reveals it.

Find inode hogs:

# Count files per top-level directory
for d in /var /data /home /tmp; do
  printf "%-8s %s
" "$d" "$(find "$d" -xdev -type f 2>/dev/null | wc -l)"
done

Pitfall: On ext4,

df
Use%

calculates based on available space after reserved blocks (5% for root). So Use% hits 100% while root still has ~5% writable space. This is a feature, not a bug. XFS has no reserved blocks; behavior differs.

3.4 Directory Usage Sorting

Purpose: df tells which partition is full; du tells which directory inside that partition consumes space.

Commands:

# Size of each immediate child, sorted (sort -h understands K/M/G)
du -sh * 2>/dev/null | sort -h

# Total size of current directory
du -sh .

# Limit depth to avoid deep traversal
du -h --max-depth=1 /var 2>/dev/null | sort -h

Expected Output:

4.0K    backup
128M    cache
1.9G    logs
18G     data

Judgment Criteria: Drill down from the largest entry until you pinpoint the exact file. This stepwise drill-down is far faster and less IO-intensive than du -a /.

Pitfalls: du -sh * expands * via shell, excluding hidden files ( .cache, .local often large). Include them with du -sh .[!.]* * 2>/dev/null | sort -h. du reports disk usage (blocks); ls -l shows logical file size. They can differ wildly (sparse files, compressed filesystems). Always trust du for actual consumption.

3.5 Conditional File Finding

Purpose: Find files by name, time, size, owner combinations—basis for cleanup and audits.

Commands:

# By name (case-insensitive)
find /var/log -iname "*.log" -type f

# Modified more than 7 days ago
find /data/tmp -type f -mtime +7

# Not accessed in 30 days
find /data -type f -atime +30

# Owned by deploy with SUID bit
find / -xdev -user deploy -perm -4000 -type f 2>/dev/null

# Combined: >100MB and modified within 3 days
find /data -type f -size +100M -mtime -3 -printf '%TY-%Tm-%Td %s %p
'

# Preview before delete (MUST run first)
find /data/tmp -type f -mtime +7 -print

# Confirm then delete (see risks)
find /data/tmp -type f -mtime +7 -delete

Judgment Criteria: -mtime +7 means "mtime older than 7 days" using 24-hour periods, not calendar days—boundary can be off by one day. -atime often unreliable on modern systems due to relatime mount option (updates atime only on mtime change or after 24h). Verify with mount | grep relatime before using for cleanup. -delete implies -depth and does not prompt for confirmation .

Pitfall: find ... -delete is a top cause of accidents. Rules:

Always run -print version first, manually review output.

Add -maxdepth to limit scope.

Exclude critical paths ( -path /data/keep -prune -o ...).

Backup or snapshot (LVM snapshot, rsync to temp) before bulk deletion.

Deletion is an irreversible production operation ; involve change management for business data.

3.6 Inspect File Type and Metadata

Purpose: Verify true file type (ignore extension), view exact permissions, owner, timestamps, inode number.

Commands:

# Real type via magic numbers
file /var/log/syslog
file -i /etc/nginx/nginx.conf   # with MIME and charset

# Full metadata
stat /etc/passwd

# Custom format: octal perms, owner:group, size, mtime, inode, name
stat -c '%a %U:%G %s %y %i %n' /etc/passwd

Expected Output:

/var/log/syslog: ASCII text
/etc/nginx/nginx.conf: text/plain; charset=us-ascii

  File: /etc/passwd
  Size: 2841        Blocks: 8          IO Block: 4096   regular file
Device: 259,2    Inode: 1048577     Links: 1
Access: (0644/-rw-r--r--)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2026-10-30 08:00:12.123456789 +0800
Modify: 2026-10-28 14:22:01.000000000 +0800
Change: 2026-10-28 14:22:01.000000000 +0800

Judgment Criteria: Access (atime), Modify (mtime), Change (ctime) have distinct meanings. Change is inode metadata change time—changing permissions or owner updates it, but content changes update both mtime and ctime. For "who modified this file", ctime is more useful than mtime. Links: 1 is hard link count. Unexpectedly high link count on a directory indicates many subdirectories or hard links. file showing data instead of text indicates binary or encoding issues. Log files showing data usually mean binary content was written (e.g., tar redirected into log) or disk corruption.

Pitfall: file relies on magic database; some formats (encrypted, custom binaries) misreport as data. More reliable text check: grep -qP '[\x00-\x08]' file (presence of control chars = not plain text).

3.7 View Text Content and Live Tail

Purpose: Examine log tails, follow new logs in real time, locate keywords in huge files.

Commands:

# Last 100 lines
tail -n 100 /var/log/nginx/error.log

# Live follow (-F reopens after logrotate rename)
tail -F /var/log/nginx/error.log

# First 20 lines (config headers, CSV headers)
head -n 20 /data/export.csv

# Search huge file with line numbers and 3 lines context
grep -n -C3 "OutOfMemory" /var/log/app/app.log

# Count occurrences
grep -c "Connection refused" /var/log/app/app.log

# Paged viewing (never cat huge files)
less /var/log/syslog

Judgment Criteria: tail -f loses track after log rotation (logrotate renames file, creates new one; -f holds old fd). tail -F detects rename and reopens—standard for production. grep exit codes: 0 = found, 1 = not found, 2 = error (missing file, permission). Scripts must use exit codes, not output parsing. Many mistakenly treat "no output" as command failure.

Pitfall: grep on tens of GB logs saturates disk IO and takes long. Alternatives:

# Only search recent 1M lines
tail -n 1000000 /var/log/app/app.log | grep "ERROR"

# Use ripgrep (multi-threaded, skips binary by default)
rg "ERROR" /var/log/app/ -n --max-count 50

# Filter by timestamp range (if logs have timestamps)
awk '$0 >= "2026-10-30 09:00" && $0 <= "2026-10-30 10:00"' /var/log/app/app.log | grep ERROR

3.8 Archive, Compress, and Sync

Purpose: Backup directories, cross-host transfer, incremental sync.

Commands:

# Archive and compress (exclude logs, caches)
tar -czf /backup/app-$(date +%F).tar.gz \
  --exclude='*.log' --exclude='node_modules' --exclude='.git' \
  -C /opt app

# List archive contents without extracting
tar -tzf /backup/app-2026-10-30.tar.gz | head -20

# Extract to specific directory (-C sets target, avoid current dir mess)
mkdir -p /tmp/restore && tar -xzf /backup/app-2026-10-30.tar.gz -C /tmp/restore

# Incremental sync: trailing slash on source is critical
rsync -avz --delete --dry-run /opt/app/ /backup/app/

Expected Output: tar -czf silent on success; tar -tzf lists paths; rsync --dry-run shows file list and summary:

sent 1.2M bytes  received 34 bytes  2.4M bytes/sec
total size is 18.9G  speedup is 15750.00 (DRY RUN)

Judgment Criteria: rsync source path with trailing slash ( /opt/app/) means "sync directory contents"; without slash ( /opt/app) means "sync directory itself" (creates app subdir at destination). This difference causes countless "backup has extra directory layer" incidents. --delete removes destination files absent from source. Dangerous —always pair with --dry-run first. --dry-run summary: high speedup indicates most files already present, only incremental transferred.

Pitfalls: tar on actively written files yields incomplete content (e.g., live database). Correct approach: databases use mysqldump / pg_dump or filesystem snapshots; app logs can be rotated via logrotate then archived. rsync --delete with failed source mount (e.g., NFS down, directory appears empty) wipes the entire destination . Guard with pre-check:

# Abort if source missing or empty
if [ ! -d /opt/app ] || [ -z "$(ls -A /opt/app)" ]; then
  echo "source missing or empty, abort" >&2
  exit 1
fi
rsync -avz --delete /opt/app/ /backup/app/

This check seems redundant but is the last gate against "backup deletes production" disasters.

Permissions and Ownership: 7 Operations

4.1 Read Permission Bits

Purpose: Translate symbolic notation like -rw-r--r-- into "who can do what".

Command: ls -l /etc/passwd /usr/bin/passwd /tmp Expected Output:

-rw-r--r--  1 root root  2841 Oct 28 14:22 /etc/passwd
-rwsr-xr-x  1 root root 68208 Feb  6  2024 /usr/bin/passwd
drwxrwxrwt 12 root root  4096 Oct 30 09:00 /tmp

Judgment Criteria: First column 10 chars split into four segments:

-  rw-  r--  r--
│   │    │    └── others
│   │    └─────── group
│   └──────────── owner
└──────────────── type: - file, d dir, l symlink, s socket, p pipe, c/b device

Each trio: r =4, w =2, x =1. Directory x means "traverse"; without it, even with r you cannot cd in, only ls names. This explains "read permission but cannot open file".

Special Bits: s in owner position ( rws) = SUID: execute as file owner. /usr/bin/passwd classic example (regular users write /etc/shadow). s in group position = SGID: on directories, new files inherit directory's group—common for team collaboration. t in others position ( rwt) = sticky bit: only file owner can delete own files in directory; /tmp uses this to prevent cross-user deletion.

Pitfall: SUID is prime target for privilege escalation. Regularly audit anomalous SUID files:

find / -xdev -perm -4000 -type f -printf '%p
' 2>/dev/null | sort

Compare against baseline; new SUID files must be investigated immediately.

4.2 Modify Permissions

Purpose: Add/remove permissions for specific roles.

Commands:

# Symbolic: owner +x, group +r, remove all from others
chmod u+x,g+r,o-rwx script.sh

# Numeric: owner rwx, group r-x, others ---
chmod 750 /data/app

# Recursive (dangerous, see risks)
chmod -R u+rwX,go-w /data/app

# Only add execute to directories, not regular files (capital X)
chmod -R a+rX /data/static

Judgment Criteria:

Capital X means "add execute only if file is a directory or already has any execute bit". Use X not x for recursive directory trees; otherwise all regular files become executable—a hidden security issue (executable configs, logs). chmod 777 means "anyone can read, write, execute". It fixes "permission denied" but introduces "anyone (including compromised low-priv process) can modify this file".

Risks of chmod -R 777 :

Web directory 777 allows webshell to write and execute = RCE door open.

Config file 777 lets any local user modify config, including authorized_keys path.

Masks root cause—real issue often SELinux context, wrong owner, or missing x on parent directory; 777 just bypasses one layer.

Alternatives in 4.3 and 4.5.

4.3 Change Owner and Group

Purpose: Assign files to correct service account.

Commands:

# Change owner and group
chown app:app /data/app/config.yml

# Change group only
chgrp www-data /var/www/html/index.html

# Recursive (caution)
chown -R app:app /data/app

# Change owner only, preserve group
chown app: /data/app

Judgment Criteria: chown -R follows symlinks? Default does not traverse symlink targets (GNU chown -R changes the symlink itself, not target). Control explicitly with -h (change link) or -L (follow link).

Risks: chown -R on large trees is slow (per-inode write) and resets SGID bit (owner change clears SUID/SGID per kernel security). If directory relies on SGID for group inheritance, chown -R breaks it—new files get default group, team collaboration breaks instantly.

Alternative: change only what's needed.

# Only change files not owned by app
find /data/app ! -user app -exec chown app: {} +

# Verify no leftovers
find /data/app ! -user app -printf '%u %p
' | head

4.4 Default Permissions via umask

Purpose: Control default permissions for newly created files, avoiding recurring "new file has wrong permissions".

Commands:

# View current umask
umask

# Temporarily set to 027 (new files 640, new dirs 750)
umask 027

# Permanent for login shells
echo 'umask 027' | sudo tee -a /etc/profile.d/umask.sh

Judgment Criteria: New file perms = 666 - umask; new dir perms = 777 - umask.

umask values:

022 : new files 644, new dirs 755 — default, world-readable

027 : new files 640, new dirs 750 — group readable, others none

077 : new files 600, new dirs 700 — owner only, sensitive data

Pitfall: umask only affects current shell and its children. systemd services, cron jobs, Docker containers each have their own umask; changing /etc/profile doesn't affect them. systemd services need UMask=0027 in unit file; Docker inherits dockerd's umask (set separately).

4.5 ACL: Grant Specific User Access

Purpose: Allow a specific user access without changing owner or others permissions—correct replacement for chmod 777.

Commands:

# View ACL
getfacl /data/app/logs

# Grant user deploy rwx
setfacl -m u:deploy:rwx /data/app/logs

# Grant group ops read-only
setfacl -m g:ops:r-x /data/app/logs

# Recursive default ACL (new files inherit)
setfacl -R -m u:deploy:rwx /data/app/logs
setfacl -R -d -m u:deploy:rwx /data/app/logs

# Remove specific user ACL
setfacl -x u:deploy /data/app/logs

# Remove all ACLs
setfacl -b /data/app/logs

Expected Output ( getfacl ):

# file: data/app/logs
# owner: app
# group: app
user::rwx
user:deploy:rwx
group::r-x
mask::rwx
other::---

Judgment Criteria: ls -l shows + at end of permission string when ACL exists. Seeing + means you must use getfacl; ls alone is insufficient. mask:: is the maximum effective permission for ACL entries. If you set u:deploy:rwx but mask is r-x, effective is r-x. This is the most common reason "ACL set but not working".

Default ACL ( -d) only applies to directories, governing newly created files' inheritance; does not affect existing files.

Pitfall: ACL requires filesystem support. ext4/xfs enable by default; NFS needs server and client support (NFSv4 native, NFSv3 needs nfs4-acl-tools with inconsistent behavior). Validate before using ACL across NFS.

4.6 Special Permission Bits

Purpose: Understand and correctly use SUID/SGID/sticky; identify anomalies.

Commands:

# Set SUID (only meaningful on binaries)
chmod u+s /usr/local/bin/helper

# Set SGID on directory (new files inherit group)
chmod g+s /data/shared

# Set sticky bit on directory (only owner deletes own files)
chmod +t /data/upload

# Numeric: 4755=SUID, 2755=SGID, 1755=sticky
chmod 4755 /usr/local/bin/helper

# Find all SUID files (audit)
find / -xdev -perm -4000 -type f 2>/dev/null

Judgment Criteria:

SUID only works on binary executables . Setting SUID on shell scripts is ineffective (kernel ignores)—many waste hours here.

Directory SGID is standard for team collaboration: chmod 2775 /data/shared + group membership = new files auto-inherit group, no manual chgrp needed.

Sticky bit on /tmp is default; prevents user A deleting user B's files. Shared upload directories should have it.

Risks: SUID binaries are primary privilege escalation targets. If a SUID program has buffer overflow or command injection, attacker gains root. Audit rules:

Establish SUID baseline ( find output archived).

Weekly diff; new entries must be owned.

Prefer sudo rules over SUID (sudo has audit logs; SUID has none).

4.7 File Attributes via chattr: Even Root Cannot Modify

Purpose: Prevent critical files from accidental deletion or tampering, including by root.

Commands:

# View attributes
lsattr /etc/passwd

# Immutable (cannot delete, rename, write, hardlink)
chattr +i /etc/passwd

# Append-only (only append, no modify/delete)
chattr +a /var/log/audit/audit.log

# Remove attribute (must do before modifying)
chattr -i /etc/passwd

Expected Output: lsattr shows ----i---------e------- /etc/passwd; i = immutable.

Judgment Criteria:

With +i, rm fails with Operation not permitted, echo >> also fails. Blocks even root (unless chattr -i first). +a suits audit logs: append-only, cannot truncate or delete; attacker clearing traces must change attribute first, which itself is audited.

Only supported on ext2/3/4, xfs, btrfs. NFS, tmpfs unsupported; chattr returns Operation not supported.

Risks: +i on wrong file breaks service startup with misleading Permission denied (not "file locked"). Record baseline before applying:

chattr +i /etc/passwd /etc/shadow /etc/sudoers
lsattr /etc/passwd /etc/shadow /etc/sudoers | tee /var/log/chattr-baseline.txt

Rollback: chattr -i <file>. If even chattr -i fails (filesystem read-only), check dmesg for IO errors.

Processes and Resources: 8 Operations

5.1 Precise Process Query

Purpose: Filter processes by CPU, memory, start time, state—not just list all.

Commands:

# Top 15 by CPU
ps -eo pid,ppid,user,stat,pcpu,pmem,etime,cmd --sort=-pcpu | head -15

# Top 15 by memory (RSS)
ps -eo pid,ppid,user,stat,pmem,rss,cmd --sort=-rss | head -15

# Only specific user
ps -u www-data -o pid,stat,pcpu,pmem,cmd

# Threads of a specific process (-L)
ps -L -p $(pgrep -f "java.*app.jar" | head -1) -o pid,tid,stat,pcpu,comm | head -20

Expected Output:

PID  PPID USER  STAT %CPU %MEM     ELAPSED CMD
18422     1 app   Ssl  45.2  8.1   3-04:12:33 python -m uvicorn app:main
 1201     1 root  Ss    2.1  0.3  21-08:44:01 /usr/bin/containerd

Judgment Criteria: STAT first char is key: R running, S interruptible sleep (normal wait), D uninterruptible sleep (waiting IO, unkillable ), Z zombie (parent didn't reap), T stopped (SIGSTOP or debugger). D state is most misjudged. Process shows D, kill -9 does nothing because it's waiting for kernel IO completion; signal handled only after syscall returns. Investigate storage ( iostat, dmesg), not process. Z zombies consume no resources but hold PIDs. Many zombies = parent bug (no wait()). Kill parent, not zombie. ELAPSED = runtime. 3-04:12:33 = 3 days 4 hours. If a process shows minutes but service ran months, it's restarting repeatedly.

Pitfall: ps aux truncates wide output; cmd column incomplete. For full command line:

tr '\0' ' ' < /proc/<pid>/cmdline; echo

Most reliable, bypasses ps column limits.

5.2 Reading top's Key Columns

Purpose: Real-time overall load distribution; identify CPU, memory, or IO bottleneck.

Commands:

top -b -n 1 -o %CPU | head -25   # batch mode, good for scripts
top -H -p <pid>                 # threads of a process

Expected Output:

top - 09:15:22 up 21 days,  3:12,  2 users,  load average: 12.40, 8.15, 5.02
Tasks: 412 total,   3 running, 408 sleeping,   1 stopped,   0 zombie
%Cpu(s): 62.3 us,  8.1 sy,  0.0 ni, 22.4 id,  6.8 wa,  0.0 hi,  0.4 si,  0.0 st
MiB Mem :  64253.0 total,   1204.3 free,  58210.1 used,   4838.6 buff/cache
MiB Swap:   8192.0 total,   8192.0 used,      0.0 free,   1024.0 avail Mem

Judgment Criteria (per line): load average three numbers = 1/5/15 min averages. Compare to CPU cores : nproc = 8, load 12.4 means 4.4 tasks queued. Sustained load > cores = overload. us high = user-space CPU intensive (compute, normal peak). sy high = kernel-space, usually frequent syscalls (small IO, network packets, lock contention). wa high = IO wait, disk bottleneck. >20% → check iostat. si / hi high = soft/hard interrupts, often NIC or disk IRQ saturating single core. st high = stolen CPU (hypervisor), typical in overcommitted VMs/containers. buff/cache is reclaimable cache, not "used". Judge memory pressure by available ( free -m avail Mem), not free.

Pitfall: top first sample (default 1.5s refresh) shows %CPU as average since process start, not instantaneous. Wait for second refresh or use top -d 2 and observe several cycles.

5.3 Find Processes by Name and Bulk Operate

Purpose: Match processes by command-line pattern, avoid manual PID copying.

Commands:

# Match process name (not args)
pgrep -a nginx

# Match full command line (-f), common for scripts with args
pgrep -af "python.*worker.py"

# Match specific user
pgrep -u www-data -a

# Bulk signal (preview list, then signal)
pgrep -af "python.*worker.py"
pkill -TERM -f "python.*worker.py"

Judgment Criteria: pgrep nginx matches process name ( comm, max 15 chars). pgrep -f matches full command line. Processes with names >15 chars (e.g., containerd-shim) won't match without -f. pkill -f with overly broad pattern (e.g., pkill -f python) kills all Python processes including monitoring agents—classic "script kills its own collector" accident.

Risks: pkill / killall are bulk termination; impact depends on pattern. Before executing:

Run pgrep -af to print match list, manually confirm.

Add more specific identifiers (script path, args).

Exclude self: pkill -f "worker.py" may kill current shell if its command line contains worker.py. Safer: capture PIDs via pgrep then kill individually.

# Safer bulk termination: exclude current shell's process tree
for pid in $(pgrep -f "python.*worker.py"); do
  [ "$pid" = "$$" ] && continue
  echo "TERM $pid $(tr '\0' ' ' < /proc/$pid/cmdline)"
  kill -TERM "$pid"
done

5.4 Process Tree

Purpose: See parent-child relationships; determine if killing a process will cascade.

Commands:

# Show subtree rooted at PID
pstree -ap <pid>

# Full process tree with PIDs
pstree -p | head -40

# Find all descendants of a PID
pstree -p <pid> | grep -oP '\(\d+\)' | tr -d '()'

Expected Output:

systemd,1 --switched-root --system
  └─nginx,1201
      ├─nginx,1202
      └─nginx,1203

Judgment Criteria:

Master process exit usually cleans up workers; worker exit doesn't affect master (master forks new).

If service process parent is 1 (systemd), it's managed by systemd; systemctl stop stops cleanly. If parent is another process (shell, supervisor), systemctl can't reach it—stop leaves leftovers.

Pitfall: Container PID 1 is container's main process, not systemd. Container pstree appears flat due to PID namespace isolation—normal, not anomaly.

5.5 Inspect Process Open Files and Ports

Purpose: Identify which process holds a file/port, or what a process has open.

Commands:

# All files opened by a PID
lsof -p <pid> | head -30

# Who holds a port
lsof -i :8080

# Who holds a file (when unmount fails)
lsof /data/app/data.db

# Deleted but still open files (cause of "missing disk space")
lsof +L1

# Files opened under a directory
lsof +D /data/app/logs

Expected Output:

COMMAND   PID USER   FD   TYPE DEVICE  SIZE/OFF   NODE NAME
java    18422 app    cwd   DIR  259,2      4096 1048577 /data/app
java    18422 app    1w    REG  259,2 12884901888 2097153 /data/app/logs/app.log
java    18422 app    5r    REG  259,2  1073741824 2097154 /data/app/data.db

Judgment Criteria: FD column: 1w = fd 1 (stdout) opened write; 5r = read-only. lsof +L1 shows NLINK = 0 for deleted-but-held files. These occupy disk space but du can't see them (directory entry gone); only df shows space used. This is the definitive answer to "deleted file but space not freed" . (deleted) marker in NAME column means same thing.

Risk: lsof scans all /proc fds; on high-process, high-fd machines (e.g., nginx with tens of thousands of connections) it's very slow (tens of seconds). Limit scope in production:

# Only specific user
lsof -u www-data -i :80

# Only specific process group
lsof -p $(pgrep -d, -f nginx)

Correct Handling of "Deleted File Space Not Freed" :

# 1. Identify holding process
lsof +L1 | awk 'NR==1 || $7>0'

# 2. Option A: Restart/reload process (safest, may impact business)
systemctl reload nginx

# 3. Option B: Truncate file content without deleting (safe for append-only logs, dangerous for data files)
: > /proc/<pid>/fd/<fd_number>

# 4. Option C: If process doesn't support reload, must restart

Option B ( : > /proc/<pid>/fd/N) zeros file size but keeps same inode; process continues writing without error. Only safe for append-only log files ; random-read/write data files will corrupt—never use on database files.

5.6 Listening Ports and Process Mapping

Purpose: Confirm service listening address, port, and process.

Commands:

# Listening TCP ports with process (need root to see others' processes)
ss -lntp

# TCP and UDP
ss -lnutp

# Specific port
ss -lntp 'sport = :8080'

Expected Output:

State  Recv-Q Send-Q Local Address:Port  Peer Address:Port  Process
LISTEN 0      511        0.0.0.0:80         0.0.0.0:*        users:(("nginx",pid=1201,fd=6))
LISTEN 0      4096       127.0.0.1:8080     0.0.0.0:*        users:(("java",pid=18422,fd=45))
LISTEN 0      128              [::]:22         [::]:*        users:(("sshd",pid=901,fd=3))

Judgment Criteria: Local Address = 0.0.0.0:80 listens all IPv4; 127.0.0.1:8080 listens only loopback— external access impossible . This is the #1 cause of "service up but external can't connect". [::]:22 is IPv6 wildcard; usually also accepts IPv4 (depends on net.ipv6.bindv6only). Recv-Q in LISTEN = completed connections not yet accepted. Persistent >0 and growing = application accept can't keep up; full connection queue piling up. Exceeds Send-Q (backlog limit) → new connections dropped or RST. Send-Q in LISTEN = backlog limit (min of somaxconn and listen() argument).

Pitfall: ss -lntp hides process names usually due to permissions (non-root can't see other users' socket ownership). Use sudo ss -lntp or run as root.

5.7 Signals and Process Termination

Purpose: Terminate processes with correct signal to avoid data corruption.

Commands:

# Graceful termination (default signal = kill -15)
kill <pid>

# Explicit signals
kill -TERM <pid>   # 15, request exit, process can cleanup
kill -INT <pid>    # 2, equivalent to Ctrl+C
kill -HUP <pid>    # 1, many services use for "reload config"
kill -QUIT <pid>   # 3, some services use for "graceful exit + dump"
kill -KILL <pid>   # 9, force kill, process cannot catch, no cleanup chance

# By name
pkill -HUP nginx

Expected Output: No output = signal sent successfully. Send success ≠ process exited ; verify with ps -p <pid>.

Judgment Criteria: SIGTERM catchable; process can save state, close connections, release locks. Use first . SIGKILL uncatchable, unignorable; kernel reclaims immediately. Costs: unwritten data lost, temp files left, lock files not released, shared memory segments not cleaned, database may enter crash recovery. SIGHUP semantics defined by program. nginx uses HUP for config reload, but many programs default to terminate on HUP. Check docs, don't guess.

Process in D state: any signal waits for syscall return, including KILL. "Unkillable" is normal; fix underlying IO.

Risks of kill -9 :

Database process : Uncommitted transactions rollback, crash recovery may take minutes, extreme cases data page corruption

Writing log/file : Buffer data lost, file may be half-written

Process holding flock : Lock released with process exit, but stale lock file may cause false detection on restart

Shared memory (SysV/POSIX) : Segments not released, ipcs -m shows leftovers, accumulation exhausts limits

Container PID 1 : Container exits, K8s shows restart

Correct Termination Sequence:

# 1. Send TERM, wait 30 seconds
kill -TERM <pid>
for i in $(seq 1 30); do
  ps -p <pid> > /dev/null || { echo "exited after ${i}s"; exit 0; }
  sleep 1
done

# 2. Still alive? Examine what it's doing
cat /proc/<pid>/status | grep -E "State|SigQ"
cat /proc/<pid>/stack 2>/dev/null   # kernel stack, D state shows where stuck
ls -l /proc/<pid>/fd | tail -10   # recent fds

# 3. Confirm stuck, not graceful shutdown, then KILL
kill -KILL <pid>

Step 2 is often skipped; people jump to -9, killing a process doing 30s cleanup (e.g., cache flush), then spend hours on data recovery.

5.8 Resource Levels: Load, Memory, IO

Purpose: One-shot view of CPU, memory, IO real-time state to locate bottleneck.

Commands:

# Load and uptime
uptime

# Memory (-m in MiB, watch available not free)
free -m

# VM stats, one line per second
vmstat 1 5

# Disk IO extended stats, one line per second (sysstat package)
iostat -xz 1 3

Expected Output ( vmstat 1 5 ):

procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
 3  0      0 120431  82304 4892012  0   0    12   340 1204 3821  8  2 89  1  0
12  4      0  98220  82304 4891200  0   0  4096 18432 4210 9842 42 12 38  8  0

Judgment Criteria: r (run queue) persistently > CPU cores = CPU shortage. b (blocked on IO) > 0 = IO bottleneck. si / so (swap in/out) non-zero and sustained = memory pressure already paging; performance cliffs. Swap actively paging = not enough memory ; ignore "some swap is fine" myth. wa high with bo (block writes) high = write IO bottleneck; bi high with wa high = read IO bottleneck. cs (context switches) abnormally high (tens/hundreds of thousands) with sy high = lock contention or many tiny threads.

Judging Real Memory Pressure:

free -m
#          total   used   free  shared buff/cache available
# Mem:     64253  58210   1204     512      4838      4312

Watch available (4312 MiB) = memory allocatable without swapping. free only 1204 but available 4312 means 3GB cache reclaimable. Judge OOM risk by available, not free.

Pitfalls:

Inside containers, free reads host memory (unless cgroup v2 memory.current), vmstat also host view. Use cgroup files:

cat /sys/fs/cgroup/memory.current   # cgroup v2
cat /sys/fs/cgroup/memory.max
# or v1
cat /sys/fs/cgroup/memory/memory.usage_in_bytes
cat /sys/fs/cgroup/memory/memory.limit_in_bytes
iostat

requires sysstat package ( apt install sysstat / dnf install sysstat). Many minimal images lack it; install offline not possible—keep on admin box.

Network: 7 Operations

Solves "why can't I connect" following OSI bottom-up: address → routing → reachability → port → application → DNS → packet capture.

6.1 Check Addresses and Routing

Purpose: Verify local IPs, interface status, default gateway, policy routing.

Commands:

# Brief mode, all interfaces at a glance
ip -br addr

# Detailed: MTU, state, stats
ip addr show dev eth0

# Routing table
ip route

# Which route to a target (most useful)
ip route get 8.8.8.8

# Policy routing (multi-homed/multi-egress essential)
ip rule show
ip route show table all | grep -v "^local\|^broadcast"

Judgment Criteria: UP = interface administratively up; LOWER_UP = physical link up (shown in ip addr as <BROADCAST,MULTICAST,UP,LOWER_UP>). UP without LOWER_UP = cable unplugged or switch port down. ip route get 8.8.8.8 explicitly tells which interface, source IP, next hop. Multi-homed "ping works but app fails" often due to wrong source IP (e.g., routed via docker0).

Non-default ip rule entries (e.g., from 10.0.3.15 lookup 100) require checking that specific table ( ip route show table 100). Only checking main table misses policy routing → "routing looks fine but doesn't work".

Pitfall: ip addr shows dynamic (DHCP) or secondary (second IP on same interface). Changes via ip addr add/del are temporary; persist via distro config (Ubuntu netplan, RHEL NetworkManager keyfile).

6.2 Connectivity Testing

Purpose: Confirm layer-3 reachability and locate packet loss hop.

Commands:

# Basic connectivity, limit count
ping -c 4 10.0.3.1

# Specify source interface (multi-homed mandatory)
ping -c 4 -I eth1 10.0.4.1

# Large packet MTU test (-M do prohibits fragmentation, -s payload size)
ping -c 2 -M do -s 1472 10.0.4.1

# Path trace + loss stats (more practical than traceroute)
mtr -rw -c 20 10.0.4.1

Expected Output ( mtr -rw -c 20 ):

HOST: app-01          Loss%  Snt  Last  Avg  Best  Wrst StDev
 1.|-- 10.0.3.1         0.0%   20   0.4  0.5  0.3  1.1  0.2
 2.|-- 10.0.0.1         0.0%   20   1.2  1.4  1.0  3.2  0.5
 3.|-- 10.0.4.1        35.0%   20  12.1 12.5 11.8 15.0  0.9

Judgment Criteria:

Intermediate hop loss but final hop clean = normal . Many routers rate-limit ICMP TTL exceeded; mtr shows 30% loss mid-path but target 0% loss → path healthy. Only final hop loss is real problem. ping -M do -s 1472 works, -s 1473 fails → path MTU = 1500 (1472 + 28 bytes ICMP/IP header). MTU mismatch symptom: "small requests OK, large responses hang"; common in VPN and cross-cloud links. ping works but port unreachable → layer 3 OK, problem at layer 4 (firewall, listen address, SELinux).

Pitfall: Many clouds/firewalls block ICMP by default; ping failure ≠ service unreachable. Use port probing (6.3) for reachability decisions.

6.3 Port Probing

Purpose: Verify target port open and TCP connection possible.

Commands:

# nc probe (-z scan only, -v verbose, -w timeout)
nc -zv -w 3 10.0.4.20 3306

# Batch multiple ports
for p in 22 80 443 3306 6379; do
  nc -zv -w 2 10.0.4.20 "$p" 2>&1 | sed "s/^/[$p] /"
done

# Bash built-in /dev/tcp (no nc needed)
timeout 3 bash -c 'cat < /dev/null > /dev/tcp/10.0.4.20/3306' && echo "open" || echo "closed"

# curl probe (distinguishes "can't connect" from "connected but error")
curl -sS -o /dev/null -w "%{http_code} connect=%{time_connect}s total=%{time_total}s
" \
  --max-time 5 http://10.0.4.20:8080/health

Expected Output: Connection to 10.0.4.20 3306 port [tcp/mysql] succeeded! Judgment Criteria:

succeeded : TCP handshake success → service listening; issue may be application layer

Connection refused : Host reachable, port not listening (or firewall REJECT) → check target ss -lntp; verify listen address not 127.0.0.1

Connection timed out : Packet dropped (firewall DROP, routing broken, host down) → check firewall rules, routing, security groups

No route to host : Layer 3 unreachable → check ip route get, ARP Connection refused vs timed out distinction is critical: former = network OK, service down; latter = network layer blocked. One word difference dictates troubleshooting direction.

Pitfall: nc has multiple implementations (OpenBSD nc, nmap-ncat, busybox nc) with differing flags. RHEL ships nmap-ncat supporting -z; some minimal images' busybox nc lacks -z —fall back to /dev/tcp.

6.4 curl: Not Just Requests, a Diagnostic Tool

Purpose: Single request yields DNS, connect, TLS, first-byte, total timing breakdown to pinpoint slowness segment.

Command:

curl -sS -o /dev/null \
  -w 'dns=%{time_namelookup} connect=%{time_connect} tls=%{time_appconnect} ttfb=%{time_starttransfer} total=%{time_total} code=%{http_code}
' \
  --max-time 10 \
  https://api.example.com/health

Expected Output:

dns=0.004 connect=0.012 tls=0.038 ttfb=0.121 total=0.124 code=200

Judgment Criteria: dns large (>100ms) → DNS slow; check /etc/resolv.conf and DNS server. connect - dns large → TCP handshake slow; high RTT or packet loss. tls - connect large → TLS handshake slow; long cert chain, OCSP validation slow, or server CPU busy. ttfb - tls large → server processing slow (app logic, DB query). total - ttfb large → response body transfer slow (large file, bandwidth limit).

Other Diagnostic Commands:

# Response headers only
curl -sSI https://api.example.com/

# Full handshake (-v), see TLS version, cert chain
curl -sv https://api.example.com/ 2>&1 | grep -E "SSL|TLS|subject|issuer|expire"

# Force protocol version and SNI
curl -sS --tlsv1.2 --resolve api.example.com:443:10.0.4.30 https://api.example.com/

# Follow redirects, show each hop
curl -sSL -w '%{url_effective} %{http_code}
' -o /dev/null https://example.com/

# Check cert expiration
echo | openssl s_client -connect api.example.com:443 -servername api.example.com 2>/dev/null \
  | openssl x509 -noout -dates -subject

Pitfall: curl uses system CA bundle by default. Minimal container images often lack ca-certificates, yielding

SSL certificate problem: unable to get local issuer certificate

. This is NOT a cert issue—it's missing client CA. Fix: install ca-certificates; never use -k to skip verification—disables MITM detection.

6.5 DNS Resolution

Purpose: Confirm domain resolves to which IP, whether cache used, if resolution times out.

Commands:

# Query DNS server directly (bypass nsswitch and local cache)
dig +short api.example.com
dig api.example.com @10.0.0.2 +noall +answer

# Specific record types
dig +short MX example.com
dig +short TXT _dmarc.example.com

# Trace full resolution chain (root to authoritative)
dig +trace api.example.com | tail -20

# Use system resolver (follows /etc/nsswitch.conf, includes /etc/hosts, systemd-resolved)
getent hosts api.example.com

# See actual DNS servers
cat /etc/resolv.conf
resolvectl status 2>/dev/null | head -20

Judgment Criteria: dig vs getent mismatch → /etc/hosts overrides DNS, or nsswitch.conf order not files dns. Classic cause of "ping works but app fails"—app uses own resolver (e.g., Go's pure Go resolver reads resolv.conf directly, ignores nsswitch). dig returns SERVFAIL = DNS server problem (upstream timeout, DNSSEC validation fail); NXDOMAIN = domain doesn't exist. Meanings completely different.

Resolution latency via

dig
Query time

or curl -w; >100ms warrants optimization.

Pitfall: /etc/resolv.conf honors max 3 nameserver entries; 4th+ ignored. Default timeout 5s, retries 2 → first DNS down causes 10s resolution stall per query. Hidden cause of "intermittent service timeouts". Mitigate with options timeout:1 attempts:2.

6.6 Packet Capture

Purpose: When all else fails, look at packets directly.

Commands:

# Capture host's port 80, 20 packets, no DNS/port resolution
tcpdump -i any -nn -c 20 host 10.0.4.20 and port 80

# Capture with ASCII payload (view HTTP plaintext)
tcpdump -i eth0 -nn -A -s0 -c 10 'tcp port 8080'

# Only TCP handshake/teardown (see if connection establishes, who closes)
tcpdump -i any -nn 'tcp[tcpflags] & (tcp-syn|tcp-fin|tcp-rst) != 0' -c 30

# Save to file for Wireshark
tcpdump -i any -nn -s0 -w /tmp/cap.pcap 'host 10.0.4.20 and port 3306'

# Count retransmissions (judge loss)
tcpdump -i any -nn 'tcp[tcpflags] & tcp-syn != 0' -c 100 -w /tmp/syn.pcap

Expected Output:

09:20:11.123456 IP 10.0.3.15.54321 > 10.0.4.20.80: Flags [S], seq 123456789, win 64240, options [mss 1460,sackOK,TS val 1 ecr 0,nop,wscale 7], length 0
09:20:11.123890 IP 10.0.4.20.80 > 10.0.3.15.54321: Flags [S.], seq 987654321, ack 123456790, win 65160, options [mss 1460,sackOK,TS val 2 ecr 1,nop,wscale 7], length 0
09:20:11.124012 IP 10.0.3.15.54321 > 10.0.4.20.80: Flags [.], ack 1, win 502, options [nop,nop,TS val 2 ecr 2], length 0

Judgment Criteria:

See [S] without matching [S.] → request sent but no reply (firewall DROP, service not listening and DROP, return routing broken).

See [S.] then client sends [R] (RST) → client rejects response (usually port not listening but REJECT, or conntrack state anomaly).

Many [TCP Retransmission] → packet loss; correlate with ss -ti retrans rate. [F] (FIN) initiator determines "who closed first". Connections killed by middleboxes (NAT, firewall) timeout show no FIN on either side → "connection hangs without error".

Risks: tcpdump on high-traffic interfaces consumes heavy CPU/memory (capture buffer); -w can fill disk in seconds. Rules:

Always use -c (packet limit) or -G (time rotation) + -W (file count limit).

Write capture to separate partition, not /.

Production: prefer -i any with precise filter to avoid full capture.

Capture may contain cleartext credentials (HTTP Basic, SQL); set file perms 600, delete after use.

Container Note: Container tcpdump sees only its network namespace. To capture host or other containers, run on host on veth / docker0 / cni0 interfaces, or nsenter -t <pid> -n tcpdump ....

6.7 Connection State Statistics

Purpose: Detect abnormal connection counts, excessive TIME_WAIT / CLOSE_WAIT, port exhaustion.

Commands:

# Summary stats (state counts, socket memory)
ss -s

# TCP connection state breakdown
ss -tan | awk 'NR>1 {print $1}' | sort | uniq -c | sort -rn

# Connections on specific port
ss -tan 'sport = :80' | wc -l

# Per-connection TCP details (cwnd, RTT, retrans)
ss -tin 'dport = :3306' | head -20

# Local port range (check port exhaustion)
sysctl net.ipv4.ip_local_port_range

Expected Output ( ss -s ):

Total: 412
TCP:   389 (estab 210, closed 120, orphaned 3, timewait 118)
Transport Total   IP     IPv6
RAW       1       0       1
UDP       8       6       2
TCP       389     350     39

Judgment Criteria:

Large timewait pileup (tens of thousands) = too many short connections; need connection pooling or tune net.ipv4.tcp_tw_reuse (note tcp_tw_recycle removed in newer kernels; old tutorials still teach it—don't use). closed includes CLOSE_WAIT. Large

CLOSE_WAIT</sub> = <strong>application not closing connections</strong> (received FIN but didn't close). This is a code bug; kernel params won't help. Identify:</li></ul><pre><code>ss -tan state close-wait | head -20
# By process
ss -tanp state close-wait | awk 'NR>1 {print $NF}' | sort | uniq -c | sort -rn
orphaned

non-zero = sockets whose owning process exited but connection remains (usually fork then parent exit).

ss -tin
retrans

field = retransmission count. Retrans rate = retrans / total; >1% indicates network quality issues.

Pitfall: ss -tan | wc -l counts lines including header (off by 1) and includes TIME_WAIT , not "active connections". Accurate active count:

ss -tan state established '( sport = :80 )' | tail -n +2 | wc -l

tail -n +2 skips header; state established filters only established. These details determine monitoring accuracy.

Five Real Troubleshooting Scenarios

Each follows: Phenomenon → Initial Judgment → Checks → Judgment → Root Cause → Fix → Verification → Rollback Plan → Retrospective.

7.1 Disk Full but du Doesn't Match

Phenomenon: App logs No space left on device ; df -h shows / 100% used, Avail 0. But du -sh /var only 8G, du -sh /* totals <30G on 200G partition. Initial Judgment: Three possibilities: inode exhaustion, deleted-but-held files, mount point covering directory. Check 1 (exclude inodes): df -i / → IUse% 3% → not inodes. Check 2 (find deleted-but-held): lsof +L1 shows two java processes holding app.log and error.log (both NLINK=0 , marked (deleted) ) totaling 18G. Check 3 (exclude mount shadowing): If lsof empty, compare df mount points vs actual dir contents with findmnt -T /data , du -sh /data , mount | grep " /data" . Judgment: du traverses directory entries; deleted files have no entry so du misses them. Inode persists (held by process fd), blocks not freed → df sees usage. This is the most common cause of df / du mismatch (>80% of cases). Root Cause: Logrotate misconfiguration. logrotate used create (rename old, create new) but app holds file descriptor (e.g., Java logback). After rename, app writes to old file (now app.log.1 ), then file deleted but fd open. Fix (choose by impact):

Option A (recommended, no downtime): Truncate via /proc fd, preserving inode:

ls -l /proc/18422/fd/1   # confirm fd
: > /proc/18422/fd/1
: > /proc/18422/fd/2
df -h /

Option B (complete): Make app reopen log file. Java apps often support kill -HUP or logback JMX trigger, or restart (with interruption).

Verification: df -h / shows Avail restored to tens of GB; lsof +L1 | grep -c deleted returns 0. Rollback: Option A irreversible (content cleared) but logs usually non-critical (archived elsewhere). If critical data file truncated, only backup restore works—hence Option A only for logs . Retrospective:

Fix logrotate config: add copytruncate (copy then truncate; app doesn't need reopen), tradeoff: may lose few lines at rotation instant.

Or move rotation into app config.

Add monitoring: df usage >85% alert, alert payload includes lsof +L1 output to avoid re-investigation.

7.2 Service Won't Start: Address Already in Use

Phenomenon: systemctl start app fails with bind: address already in use ; ps aux | grep app shows nothing. Initial Judgment: Port held by another process, or old process socket in TIME_WAIT , or stale listening socket. Check 1 (who's listening): ss -lntp 'sport = :8080' reveals python3 PID 9021 listening on 127.0.0.1:8080 . ps aux | grep app missed it because command line lacks "app" (e.g., python3 -m http.server 8080 or renamed). Check 2 (if ss empty but error persists): ss -lntp | grep 8080 , lsof -i :8080 , check for D state processes. ss shows port occupied but Process column empty → holder in another PID namespace (container) or permission issue. Use sudo ; if container, docker ps / crictl ps . Check 3 (TIME_WAIT bind failure): ss -tan state time-wait 'sport = :8080' | wc -l . TIME_WAIT does not block bind (unless SO_REUSEADDR unset). Most frameworks set it; if truly the cause (custom socket code), fix by setting SO_REUSEADDR , not waiting 2MSL. Root Causes (three):

Stale process listening (most common). Previous systemctl stop didn't clean up, or manual instance started.

systemd socket activation ( .socket unit) holding port. Check: systemctl list-units --type=socket | grep 8080.

Container port mapping leftover. docker ps shows no container but docker-proxy process remains: ps -ef | grep docker-proxy | grep 8080.

Fix:

A: Verify process identity/start time ( ps -o pid,ppid,lstart,cmd -p 9021). If stale, kill -TERM for graceful exit; if holds data files, avoid -9 (data corruption risk).

B: systemctl stop <name>.socket or change service listen port.

C: systemctl restart docker (affects all containers, needs window) or handle stray docker-proxy individually.

Verification: ss -lntp 'sport = :8080' empty; systemctl start app succeeds; curl health check returns 200. Rollback: If wrong process killed, restart its service. Before kill , must confirm PID's command line —non-negotiable step. Retrospective: ps aux | grep xxx by keyword is inherently unreliable. Correct posture: "reverse lookup from port" ( ss -lntp ) or "reverse lookup from file" ( lsof &lt;file&gt; )—these two directions are definitive.

7.3 Permission Denied: Three-Layer Investigation

Phenomenon: cat /data/app/config.yml returns Permission denied ; ls -l shows -rw-r--r-- app app , current user in app group. Initial Judgment: Permission bits look fine; issue in one of three: missing x on path directory, SELinux context mismatch, or ACL/mask blocking. Check 1 (traverse path execute bits): namei -l /data/app/config.yml reveals /data/app is drwxr-x--- root root —current user neither root nor in root group, lacks x , cannot traverse. File perms are r-- but unreachable. Judgment: Directory x = traverse permission. Without it, full path known but inaccessible. namei -l lists each level, instantly shows break point—faster and less error-prone than stepwise ls -l . Check 2 (exclude SELinux on RHEL/CentOS/Rocky): getenforce , ls -Z /data/app/config.yml , ausearch -m avc -ts recent . If Enforcing and ausearch shows denied , SELinux blocking. Check 3 (exclude ACL): getfacl /data/app/config.yml . If output has mask::r-- but user entry rwx , effective is r-- (mask truncation). Root Causes & Fixes:

A. Path missing x: chmod o+x /data/app or chmod g+x /data/app. Never chmod -R o+x /data/app —makes all files executable (wrong). Only directories: find /data/app -type d -exec chmod o+x {} +.

B. SELinux context wrong (common when moving files from /root to /var/www): restorecon -Rv /var/www/html or

semanage fcontext -a -t httpd_sys_content_t "/data/app(/.*)?"; restorecon -Rv /data/app

.

C. ACL mask truncation: setfacl -m m::rwx /data/app/config.yml.

Verification: sudo -u app cat /data/app/config.yml &gt; /dev/null &amp;&amp; echo "OK" . Test as target user, not root—root can read doesn't mean app can; easiest self-deception. Rollback: chmod revert to original ( stat -c %a recorded before change). restorecon idempotent. semanage fcontext -d removes added rule. Retrospective: Permission denied has four sources (DAC, path traverse, SELinux, ACL). Investigation order: namei -l → getenforce → getfacl . Never first reflex chmod 777 —hides problem, and when SELinux blocks, 777 does nothing.

7.4 Process Hang: Unresponsive but Unkillable

Phenomenon: Service unresponsive; systemctl restart hangs; kill -9 no effect; process state D . Initial Judgment: D state (uninterruptible sleep) = process waiting for kernel syscall completion, usually IO. Signals wait for syscall return → unkillable. Check 1 (confirm state and block point): ps -o pid,stat,wchan:30,cmd -p &lt;pid&gt; , cat /proc/&lt;pid&gt;/stack , cat /proc/&lt;pid&gt;/wchan . wchan shows rpc_wait_bit_killable (NFS wait) or io_schedule (block device IO)—directly identifies syscall class. Check 2 (IO and storage health): iostat -xz 1 3 , dmesg -T | tail -50 | grep -iE "error|timeout|reset|I/O" . Expect disk errors like nvme0n1: I/O Cmd(0x2) @ LBA 12345678, 256 blocks, I/O Error . Root cause: disk IO errors, process reads/writes never complete → stuck in D . Check 3 (if NFS): mount | grep nfs , test server reachability with timeout. NFS hard mount defaults to infinite retry on server down. Root Causes: A. Local disk failure (bad sectors, controller timeout, SSD wear-out). B. NFS/CIFS server unreachable, client hard mount infinite retry. C. Storage backend (SAN, cloud disk) throttling or flapping. Fixes:

A: D processes unkillable via signals; wait for IO timeout (minutes to forever) or reboot. Before reboot, check filesystem: fuser -vm /data, umount -l /data (lazy unmount, dangerous, loses unwritten data).

B: Emergency umount -f -l (force lazy unmount) lets process get IO error and exit. Long-term: use soft,timeo (timeout but may read partial) or hard,intr (interruptible by signal).

C: Engage storage team; local cannot fix.

Verification: dmesg IO errors gone; ps -p &lt;pid&gt; shows gone; dd if=/dev/zero of=/data/.io_test bs=1M count=100 oflag=direct &amp;&amp; rm -f /data/.io_test confirms RW works. Rollback: None. IO errors are hardware/storage; only fix hardware or switch storage. Reboot must ensure data consistency (DB clean shutdown first, else long recovery). Retrospective: When kill -9 fails, don't retry. D state is kernel wait; user-space useless. Correct action: check wchan and dmesg to pinpoint IO path. Also, monitor D state process count —early storage failure signal: ps -eo stat= | grep -c '^[[:space:]]*D' Sustained >0 and growing → investigate storage.

7.5 Ping Works but Service Unreachable

Phenomenon: ping 10.0.4.20 OK; curl http://10.0.4.20:8080/ returns Connection timed out . Initial Judgment: Layer 3 OK, layer 4 blocked. Four directions: service not listening, listening on 127.0.0.1 , firewall blocking, return routing broken. Check 1 (target listen address): On 10.0.4.20: ss -lntp 'sport = :8080' . If shows 127.0.0.1:8080 , root cause = "listen only loopback". Most common cause (>50%) , especially when app config has host: localhost . Check 2 (if listening on 0.0.0.0 , check firewall): nft list ruleset , iptables -L INPUT -n -v --line-numbers , firewall-cmd --list-all . Look for DROP / REJECT hitting 8080. iptables -L -v packet counters show rule hits. Check 3 (SELinux port labels on RHEL): semanage port -l | grep 8080 . If 8080 not allowed, SELinux blocks bind. ausearch -m avc has records. Check 4 (return routing): On target: ip route get 10.0.3.15 . If return path uses wrong interface (default route points wrong gateway), "request arrives, response can't return". ping may work (ICMP routed correctly) but TCP fails. Check 5 (packet capture to confirm arrival): On target: tcpdump -i any -nn -c 10 'tcp port 8080' . See [S] no [S.] → local firewall/SELinux blocked. No packets at all → dropped in middle (security group, upstream firewall, routing). See [S] and [S.] but client times out → return routing issue. Root Causes (by probability):

App binds 127.0.0.1 (50%+).

Firewall/security group not allowing.

SELinux port label missing.

Return routing wrong (multi-homed).

Middle device (NAT, LB) session table full.

Fixes:

Change app config bind to 0.0.0.0, restart.

Allow port (firewall change = high-risk):

firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="10.0.3.0/24" port port="8080" protocol="tcp" accept'; firewall-cmd --reload; firewall-cmd --list-all

.

SELinux add port label: semanage port -a -t http_port_t -p tcp 8080.

Fix routing ( ip route temporary; persist via network config).

Verification: Client curl returns 200; target local curl http://127.0.0.1:8080/health also 200. Both must succeed. Rollback: Backup firewall rules before change ( iptables-save &gt; /root/iptables-$(date +%F).bak or firewall-cmd --list-all &gt; /root/fw.bak ); restore with iptables-restore . firewall-cmd --reload atomic—no half-applied state. Retrospective: ping only proves ICMP reachability, not TCP. Troubleshooting order: listen address → firewall → SELinux → routing → packet capture. Start with most likely, each step backed by command output evidence—no guessing.

Dangerous Commands and Safe Alternatives

Common trait: irreversible after execution . rm -rf /path → unrecoverable, typo = disaster. Safe: ls confirm first; use trash-cli; protect critical dirs with chattr +i. rm -rf $VAR/ → empty var becomes rm -rf /. Safe: rm -rf "${VAR:?}/" (exits if var unset). chmod -R 777 → destroys all security boundaries. Safe: chown + setfacl precise grants. chown -R → slow, resets SGID. Safe: find ! -user X -exec chown. kill -9 → data loss, orphan locks, possible DB corruption. Safe: -TERM, wait 30s, then -KILL. pkill -f python → over-match kills monitoring/other services. Safe: pgrep -af preview, add path specifics. find -delete → no confirmation, unrecoverable. Safe: -print preview, add -maxdepth. > file → truncates, content lost. Safe: cp file file.bak first, or truncate -s 0 (explicit). dd if=... of=/dev/sdX → wrong device destroys disk. Safe: lsblk confirm, use oflag=direct, test in staging. mkfs.* → formats, all data gone. Safe: blkid confirm no FS, mount confirm not mounted. mv a b → silently overwrites existing target. Safe: mv -n (no overwrite) or mv -i (prompt). curl ... | bash → executes unreviewed remote script. Safe: curl -o download, less review, then execute. tar -xzf to current dir → overwrites same-name files, may extract ../ paths. Safe: tar -xzf x.tar.gz -C /target, preview with -tzf first. rsync --delete → empty source deletes target. Safe: --dry-run, add source non-empty check. iptables -F → flushes all rules, SSH may break. Safe: iptables-save backup, use iptables-restore for rollback.

On Empty Variable: Classic shell script disaster:

# Dangerous: if $DIR empty, equals rm -rf /*
DIR=/data/tmp
rm -rf $DIR/

# Safe: exit if var unset/empty
rm -rf "${DIR:?DIR is not set}/"

${VAR:?message} prints message to stderr and exits (non-interactive shell exit 1). This one construct prevents most "script deletes everything" accidents. On curl | bash : Even trusted source risks "download hijacked" and "version silently changed". Production should pin version + verify hash:

URL="https://example.com/install.sh"
EXPECTED_SHA256="a1b2c3..."
curl -fsSL "$URL" -o /tmp/install.sh
echo "${EXPECTED_SHA256}  /tmp/install.sh" | sha256sum -c - || { echo "checksum mismatch"; exit 1; }
less /tmp/install.sh   # human review
bash /tmp/install.sh

Writing Commands as Scripts: Safety Templates

Ad-hoc commands can be sloppy; scripts must handle: spaces in paths, command failures, interruption, bulk operation collateral damage.

9.1 Basic Skeleton

#!/usr/bin/env bash
# Purpose: clean /data/tmp files older than 7 days
# Depends: find (GNU findutils), flock (util-linux)
# Usage: clean_tmp.sh [--apply], default dry-run
set -Eeuo pipefail   # -E: ERR trap in functions
IFS=$'
\t'         # avoid word splitting on spaces in paths

readonly TARGET_DIR="/data/tmp"
readonly KEEP_DAYS=7
readonly LOG_FILE="/var/log/clean_tmp.log"
readonly LOCK_FILE="/var/lock/clean_tmp.lock"

log() { printf '%s [%s] %s
' "$(date '+%F %T')" "$$" "$*" | tee -a "$LOG_FILE"; }
die() { log "ERROR: $*"; exit 1; }

# On error, print line and command for debugging
trap 'log "FAILED at line $LINENO: $BASH_COMMAND (exit=$?)"' ERR
# On interrupt, log and exit cleanly
trap 'log "INTERRUPTED by signal"; exit 130' INT TERM

set -Eeuo pipefail breakdown: -e: exit on command failure (except in if / while conditions). -u: error on undefined variable—catches ${DIR}/ empty accidents. -o pipefail: pipeline fails if any command fails (default only last command matters). -E: ERR trap inherits into functions and subshells.

IFS=$'\n\t' removes space as delimiter; default IFS includes space, causing for f in $list to split filenames with spaces.

9.2 Pre-checks and Dry-run

main() {
  [ "$(id -u)" -eq 0 ] || die "must run as root"
  [ -d "$TARGET_DIR" ] || die "target dir not found: $TARGET_DIR"
  command -v find >/dev/null || die "find not found"

  # Whitelist block: refuse to operate on critical paths even if misconfigured
  case "$TARGET_DIR" in
    /|/data|/var|/home) die "refusing to operate on $TARGET_DIR" ;;
  esac

  # Single instance: prevent cron overlap
  exec 9>"$LOCK_FILE"
  flock -n 9 || die "another instance is running"

  local apply=0
  [ "${1:-}" = "--apply" ] && apply=1

  local count
  count=$(find "$TARGET_DIR" -maxdepth 2 -type f -mtime "+${KEEP_DAYS}" -print | wc -l)
  log "matched ${count} files older than ${KEEP_DAYS} days in ${TARGET_DIR}"

  if [ "$apply" -eq 0 ]; then
    find "$TARGET_DIR" -maxdepth 2 -type f -mtime "+${KEEP_DAYS}" -print
    log "dry-run mode, nothing deleted. rerun with --apply"
    return 0
  fi

  # Interactive confirmation only when run from terminal
  if [ -t 0 ]; then
    read -r -p "Delete ${count} files? type 'yes' to continue: " ans
    [ "$ans" = "yes" ] || die "aborted by user"
  fi

  find "$TARGET_DIR" -maxdepth 2 -type f -mtime "+${KEEP_DAYS}" -print -delete \
    | tee -a "$LOG_FILE" | wc -l
  log "done"
}

main "$@"

Key designs: case whitelist block: critical paths ( /, /data) listed as forbidden; even if config wrong, script refuses. More reliable than "human remembers to check". flock -n: non-blocking lock; if previous run still going, new instance exits immediately. Prevents two instances deleting simultaneously (second would error on missing files or delete files first instance processing). [ -t 0 ]: only prompt for confirmation in interactive TTY. Cron has no TTY, won't hang on read —common cause of "script works in terminal, hangs in cron". -print -delete combo: prints then deletes; logs retain full record of what was deleted for audit.

9.3 Paths and Quoting

# Wrong: fails on spaces
for f in $(find /data -name "*.log"); do
  rm "$f"; done

# Correct: -print0 + read -d ''
while IFS= read -r -d '' f; do
  rm -- "$f"
done < <(find /data -name "*.log" -print0)

# Simpler and safer: -exec, no shell involved
find /data -name "*.log" -exec rm -- {} +

Three details: -print0 + read -d '' uses NUL delimiter; handles any filename (including newlines). rm -- "$f": -- means "end of options", prevents filenames starting with - being interpreted as flags. -exec ... {} + faster than -exec ... \; (batches args, fewer forks) and safer than for loops.

9.4 Exit Codes and Idempotence

# Function returns explicit, don't rely on last command
check_disk() {
  local usage
  usage=$(df --output=pcent / | tail -1 | tr -dc '0-9')
  if [ "$usage" -ge 90 ]; then
    log "disk usage ${usage}% exceeds threshold"
    return 1
  fi
  return 0
}

# Idempotent: repeated runs produce same result
ensure_dir() {
  local d="$1"
  [ -d "$d" ] || mkdir -p "$d"
}

Idempotence matters: script interrupted can be re-run without failing on "directory already exists". Cron jobs, deploy scripts must be idempotent; otherwise every failure requires manual intervention.

9.5 Encoding and Permissions

# Script must be UTF-8 no BOM, LF line endings (not CRLF)
file deploy.sh
# Expected: POSIX shell script, ASCII text executable
# If shows "with CRLF line terminators", execution fails with $'\r': command not found

# Fix CRLF
sed -i 's/\r$//' deploy.sh

# Permissions: 755 for executable scripts, 600 for credential files
chmod 755 deploy.sh
chmod 600 /etc/app/credentials.env

Windows-edited scripts copied to Linux most often break due to CRLF and BOM. BOM breaks shebang ( #!/usr/bin/env bash gets three extra bytes) → error bad interpreter: No such file or directory —looks like "bash not installed" but is encoding issue.

30 Operations Quick Reference Index

Previous sections organized by "why"; this index by "what" for field lookup.

File & Disk

List directory (hidden, time/size sort): ls -alh / ls -lht / ls -lhS Find large files: find / -xdev -type f -size +1G -printf '%s\t%p\n' Space and inodes: df -hT / df -i Directory usage sort: du -sh * | sort -h Conditional find: find <path> -type f -mtime +7 -print Type and metadata: file / stat -c '%a %U:%G %s %y %i %n' View content and tail: tail -F / grep -n -C3 / less Archive and sync: tar -czf /

rsync -avz --delete --dry-run

Permissions & Ownership

Read perms: ls -l / stat -c %a Change perms: chmod 750 / chmod -R a+rX Change owner: chown app:app / find ! -user app -exec chown Default perms: umask 027 ACL: getfacl / setfacl -m u:deploy:rwx Special bits: chmod u+s / g+s / +t; find -perm -4000 File attributes: lsattr / chattr +i /

chattr +a

Processes & Resources

Precise process query: ps -eo pid,ppid,stat,pcpu,pmem,etime,cmd --sort=-pcpu Real-time resources: top -b -n1 / top -H -p <pid> Match by name: pgrep -af / pkill -TERM -f Process tree: pstree -ap <pid> Open files: lsof -p <pid> / lsof +L1 / lsof -i :8080 Listening ports: ss -lntp Terminate process: kill -TERM → wait → kill -KILL Resource levels: uptime / free -m / vmstat 1 /

iostat -xz 1

Network

Addresses and routing: ip -br addr / ip route get <ip> Connectivity and path: ping -c4 / mtr -rw -c20 Port probe: nc -zv -w3 <host> <port> HTTP diagnostics:

curl -w 'dns=%{time_namelookup} connect=%{time_connect} ttfb=%{time_starttransfer}'

DNS: dig +short / getent hosts Packet capture: tcpdump -i any -nn -c20 'tcp port 8080' Connection states: ss -s /

ss -tan state established

Summary

Of these 30 operations, the truly daily-used ones are fewer than 10: df , du , find , tail -F , grep , ps , ss , lsof , curl , tcpdump . The other 20 are "rarely used but lifesaving when needed"—e.g., lsof +L1 (mystery disk space loss), namei -l (permission denied), wchan (unkillable process), ss -tin (slow connections). The dividing line in mastering these commands is not "remembering flags" but three things: First, know how to read output. df 's Use% and Avail must be read together; top 's wa and iostat 's %util together; ss 's Recv-Q means different things in LISTEN vs ESTAB. Same number, opposite conclusions in different contexts—commands themselves don't teach this. Second, know the side effects. chmod -R 777 fixes permission but destroys security boundaries; kill -9 fixes stuck process but loses data and leaves locks; rm has no recycle bin. Internalizing these costs matters more than memorizing flags. Third, know what to check next. This is core troubleshooting skill. ping works but port fails → check listen address; Connection refused vs timed out point to completely different directions; df full but du mismatch → lsof +L1 . These "decision branches" form diagnostic paths, and paths can be trained and reviewed. Final advice: write your common diagnostic paths into scripts . Not for automation, but for codification. The command sequence you type during each incident becomes team standard operating procedure when scripted—next person runs it and gets identical results. Add set -euo pipefail , dry-run, logging, exit codes; it becomes an executable runbook.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

Process ManagementLinuxTroubleshootingNetworkingSystem AdministrationCommandsPermissionsFile Management

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion