Introduction
Linux command-line tools give system administrators direct access to process state, disk usage, network activity, service configuration, logs, and permissions. The most useful tools also expose details that a graphical dashboard tends to hide, including kernel messages, open file descriptors, mount relationships, scheduler behavior, and resource contention.
This guide works through the commands that matter during routine operations and incident response. You will find concrete examples for inspecting a running system, tracing resource use, verifying storage conditions, testing DNS and HTTPS, reading service state, and handling common failures with clear error messages. Commands are intended for common Linux distributions using Bash and systemd, but many of them also work on other Unix-like systems.
Use the examples with care. Commands that terminate processes, modify partitions, change firewall rules, or overwrite files should be reviewed before execution, especially on production hosts.
Build a reliable baseline before troubleshooting
Begin by recording the current operating system, kernel, architecture, uptime, and hostname. This information establishes whether the host matches the expected deployment and helps explain version-specific behavior.
cat /etc/os-releaseuname -ahostnamectluptimewho -bThe /etc/os-release file usually provides a more reliable distribution name than commands that attempt to infer it from package metadata. In containers, the file may still describe the host image, so also check whether the environment is containerized:
test -f /.dockerenv && echo "Docker container"systemd-detect-virt 2>/dev/null || truegrep -E 'docker|containerd|kubepods' /proc/1/cgroup 2>/dev/nullCreate a small collection directory for diagnostic output. Run each command with a timestamp, redirect both standard output and standard error, and preserve the results before restarting services or changing kernel parameters.
mkdir -p ~/diagnostics/$(date +%Y%m%d-%H%M%S)DIAG=~/diagnostics/$(date +%Y%m%d-%H%M%S)
{ echo "=== OS ===" cat /etc/os-release echo echo "=== KERNEL ===" uname -a echo echo "=== UPTIME ===" uptime} > "$DIAG/system.txt" 2>&1This baseline takes little time and prevents a common mistake: attributing a new symptom to software when the cause is an earlier kernel update, disk exhaustion, failed mount, or altered time synchronization.
Inspect processes and resource pressure
ps provides a snapshot of processes. Use it first to identify the highest CPU and memory consumers, then use top, htop, or pidstat for a live view.
ps aux --sort=-%cpu | head -n 15ps aux --sort=-%mem | head -n 15ps -eo pid,ppid,user,stat,%cpu,%mem,etime,cmd --sort=-%cpu | head -n 20The STAT column contains useful state information:
Rmeans the process is running or eligible to run.Smeans it is sleeping and waiting for an event.Dmeans it is waiting on uninterruptible I/O, often a sign of storage or network trouble.Zmeans the process has terminated but has not been reaped by its parent.Tmeans the process has been stopped.
A large number of processes in D state deserves investigation. Use iostat to distinguish CPU pressure from blocked storage I/O.
iostat -xz 1 5On Debian and Ubuntu, install the package if needed:
sudo apt-get install sysstatOn RHEL-family systems:
sudo dnf install sysstatThe %util column reports how busy the device was during each sampling interval. It can reach 100% on some devices even when throughput remains reasonable, so do not use it alone to diagnose saturation. Compare %await, r/s, w/s, and aqu-sz. A high await value paired with low throughput usually indicates slow storage response or congestion.
For per-process resource usage, pidstat is often easier to interpret than top:
pidstat -u -r -d -p ALL 1 10The -u section reports CPU, -r reports memory, and -d reports disk I/O. Replace ALL with a process ID when the target is known:
pidstat -u -r -d -p 1234 1 10free clarifies how the kernel is using RAM. Available memory is more useful than the free column because Linux uses otherwise unused RAM for caches.
free -hInterpret available rather than assuming that low free means memory exhaustion. Sustained low available memory, high swap activity, and a growing OOM event count indicate pressure. Check the kernel log for out-of-memory events:
journalctl -k --since "1 hour ago" | grep -Ei "out of memory|oom|killed process"On systems without persistent journal storage, try the kernel ring buffer:
dmesg -T | grep -Ei "out of memory|oom|killed process"Read file descriptors and trace open resources
A service may appear healthy while holding too many sockets or database connections. lsof lists open files and the processes that own them.
sudo lsof -p 1234sudo lsof -i -nPsudo lsof -iTCP:443 -sTCP:ESTABLISHEDThe -n option prevents reverse DNS lookups, which can make output faster and more consistent. Add -P when you need numeric port numbers.
If lsof is unavailable, inspect /proc directly:
ls -l /proc/1234/fdreadlink /proc/1234/fd/* 2>/dev/nullTo locate a process using a particular port with tools that are commonly preinstalled:
sudo ss -lntp 'sport = :443'sudo ss -lntup | grep ':443'A typical listener entry looks like this:
LISTEN 0 511 0.0.0.0:443 0.0.0.0:* users:(("nginx",pid=812,fd=6))The bind address matters. 127.0.0.1:443 accepts traffic only from the local host, while 0.0.0.0:443 accepts traffic from every local IPv4 address. *:443 normally indicates IPv6 wildcard behavior and may accept IPv4 traffic as well, depending on the socket settings.
A process can inherit file descriptors from its parent. When examining a service that appears to hold an unexpected socket, inspect the entire process tree and systemd unit:
pstree -aps 1234systemctl status nginx.service --no-pagersystemctl show nginx.service -p MainPID -p ControlGroupFollow logs across services and boots
journalctl is the primary log interface on systemd hosts. It can filter by unit, boot, priority, time range, process, and executable.
journalctl -u nginx.service --since "30 minutes ago"journalctl -u nginx.service -p warning..alert --since todayjournalctl -u nginx.service -fjournalctl -u nginx.service --since "2026-11-30 08:00:00" \ --until "2026-11-30 09:00:00"The priority range in the second command includes warning, error, critical, alert, and emergency messages. Lower-priority informational records are excluded.
Inspect a specific boot when a service fails after a reboot:
journalctl --list-bootsjournalctl -b -1 -u nginx.servicejournalctl -b -1 -p errUse -o short-iso when correlating application events with remote systems. UTC timestamps avoid confusion when servers run in different time zones.
journalctl -u app.service --since today -o short-iso --no-pagerFor file-based logs, grep and awk remain useful. Here are two practical examples:
grep -iE "timeout|connection refused|permission denied" /var/log/app.logawk '$1 == "ERROR" {print strftime("%F %T"), $0}' app.logUse journalctl --disk-usage before disabling persistent logs. Journal files can consume significant space on hosts with noisy services.
journalctl --disk-usagesudo journalctl --vacuum-size=500MThe vacuum command removes older archived journal data until the target size is reached. It does not delete active journal files.
Check disk usage before deleting files
Use df for filesystem capacity and du for directory sizes. These tools answer different questions and should not be substituted for one another.
df -hTdf -ihsudo du -xhd1 /var 2>/dev/null | sort -hThe -x flag keeps du on one filesystem, which prevents mounted network or virtual filesystems from distorting the result. The -h flag selects human-readable units, and -d 1 limits output to immediate children.
A full filesystem may still have available inodes. The following output points to metadata exhaustion rather than a block-space shortage:
Filesystem Inodes IUsed IFree IUse% Mounted on/dev/sda1 655360 655320 40 100% /Find directories that contain many deleted but still-open files:
sudo lsof +L1A deleted file can keep disk space occupied until the process holding its file descriptor closes it. Restarting the owning process often releases the space, but treat that as an operational action rather than an automatic fix.
For large files, find can locate candidates without traversing other mounted filesystems:
sudo find /var -xdev -type f -size +500M -printf '%s %p\n' 2>/dev/null | sort -nr | head -n 30Avoid deleting files solely because they are large. Database files, sparse files, virtual disks, and active logs may behave differently from ordinary documents. Check ownership, path, modification time, and whether a service is using the file.
Inspect disks, partitions, and mount failures
lsblk presents the block-device hierarchy. It is often clearer than reading raw partition tables.
lsblk -o NAME,TYPE,SIZE,FSTYPE,FSAVAIL,FSUSE%,MOUNTPOINTSsudo fdisk -lsudo parted -lUse blkid to inspect filesystem labels and UUIDs. UUIDs are safer than device names in persistent configuration because device letters can change between boots.
sudo blkidls -l /dev/disk/by-uuid/The mount table may contain stale entries after a removable disk disappears or a network filesystem fails:
findmnt --verify --verbosefindmnt -t ext4,xfsA real mount failure often looks like this:
mount: /data: wrong fs type, bad option, bad superblock on /dev/sdb1, missing helper program for fstype, or other error.Check the device, partition, filesystem type, and mount options in that order. For ext4, run a read-only check after unmounting the filesystem:
sudo umount /datasudo e2fsck -fn /dev/sdb1The -n flag answers yes without making changes, while -f forces a check. Never run e2fsck on a mounted filesystem because repair operations can corrupt it further.
For XFS, use xfs_repair -n against an unmounted filesystem:
sudo xfs_repair -n /dev/sdb1XFS repair has restrictions, so review the exact error and current filesystem state before modifying it.
Monitor disk I/O and network traffic
iostat measures block-device activity, while sar provides historical performance data when the sysstat collector is enabled. Check whether collection is active:
systemctl status sysstat.service --no-pagersar -d -s 10:00:00 -e 11:00:00sar -u ALL 1 10For network errors and packet counters, use ip and /proc/net/dev:
ip -brief addressip routeip -s linkcat /proc/net/devip -s link reports packets, bytes, dropped packets, and errors for each interface. An increasing dropped or errors count can indicate a queue, driver, cabling, MTU, or host offload problem. A zero error count does not prove the network path is healthy because problems may occur upstream.
Capture packets with tcpdump when you need to inspect the wire:
sudo tcpdump -ni any 'tcp port 443' -w /tmp/https-traffic.pcapRead the capture on another terminal:
sudo tcpdump -ni any -r /tmp/https-traffic.pcapLimit the capture scope and duration. Capturing all traffic on a busy host can consume disk space, add overhead, and expose sensitive data. Stop tcpdump with Ctrl+C.
For DNS checks, resolve names independently of the application:
dig example.com Adig example.com AAAAdig @1.1.1.1 example.com Adig example.com MXA missing dig package can be installed as dnsutils on Debian or Ubuntu and bind-utils on RHEL-family systems.
Test HTTPS and the TLS handshake:
curl -I --connect-timeout 5 https://example.comcurl -v --connect-timeout 5 https://example.com 2>&1 | head -n 40openssl s_client -connect example.com:443 -servername example.com </dev/nullCommon curl failures have distinct causes:
Could not resolve host: Connection timed outThis message can mean DNS resolution failed, although some curl versions print the same wording for different stages. Reproduce it with dig and compare the resolver in /etc/resolv.conf.
curl: (7) Failed to connect to example.com port 443 after 0 ms: Couldn't connect to serverThe host resolved, but the TCP connection failed. Check the listener, firewall, routing, and whether the service accepts traffic on that interface.
SSL certificate problem: unable to get local issuer certificateThe server certificate is presented, but the client cannot verify its chain. Check the certificate’s issuer, expiration, and the trust store available to the calling application.
Control services and inspect failures
systemctl is the main control interface for systemd services. The status command shows recent journal entries and the unit’s current state.
systemctl status nginx.service --no-pager -lsystemctl is-enabled nginx.servicesystemctl is-active nginx.serviceA failed service often states its exit code in the status output:
Active: failed (Result: exit-code) since Mon 2026-11-30 08:15:42 UTC; 4min agoRead the preceding journal entries instead of restarting immediately:
journalctl -u nginx.service -n 100 --no-pagerjournalctl -u nginx.service --since "10 minutes ago" -p warning..alertTest the unit configuration before restarting:
sudo nginx -tsudo systemd-analyze verify /etc/systemd/system/example.servicesystemd-analyze verify can report syntax and dependency problems, although it does not guarantee the application will start successfully.
After changing a unit file, reload systemd and restart the affected service:
sudo systemctl daemon-reloadsudo systemctl restart example.serviceChanging the unit file does not cause systemd to reread it automatically.
Use systemctl list-units --failed to identify failed units on the host:
systemctl list-units --failed --no-pagerA failed mount or dependency may cause a service to remain in a failed state. Check systemctl list-dependencies and the corresponding unit logs before changing dependency ordering.
Read configuration without changing it
Most command-line tools offer a validation or dry-run mode, but the exact flags vary. For Nginx, use:
sudo nginx -TThe output includes the main configuration and included files. Search it with grep when needed:
sudo nginx -T 2>&1 | grep -nE "server_name|listen|proxy_pass"The -T option tests the configuration and dumps the expanded configuration. It does not reload Nginx.
For Apache HTTP Server:
sudo apachectl configtestsudo apachectl -Ssudo apachectlctl -M 2>/dev/null || trueCorrect the accidental command above before running it. The valid commands are:
sudo apachectl configtestsudo apachectl -Ssudo apachectl -MFor HAProxy, systemd manages the process, but the binary can validate its configuration:
sudo haproxy -c -f /etc/haproxy/haproxy.cfgFor Postfix:
sudo postfix checkpostconf > /dev/nullFor an SSH daemon:
sudo sshd -tsudo sshd -T | grep -E '^(port|permitrootlogin|passwordauthentication|pubkeyauthentication)'sshd -t reports invalid configuration. sshd -T prints the effective configuration, including defaults, which is useful when the active file is shorter than the final behavior suggests.
Keep existing sessions open until a configuration change is verified. If an SSH daemon restart breaks remote access, use a second session or the provider’s console.
Diagnose disk and inode exhaustion
A full filesystem can prevent services from writing logs, rotating files, saving sessions, or creating lock files. The first symptoms often appear in application logs:
No space left on deviceConfirm capacity at the exact mount point:
df -h /df -ih /findmnt -T /var/logThe findmnt -T form matters because /var or /var/log may live on a separate filesystem.
If the block count is full but inodes are available, remove or rotate safe files. Common cleanup targets include stale journal archives, old package caches, and expired temporary files.
sudo journalctl --vacuum-size=500Msudo apt-get cleansudo dnf clean allDo not remove package database files or active log files with rm while services are running. A package manager may restore package metadata, but deleting it manually can cause unrelated failures and unsupported system states.
Check inode usage:
sudo find /var -xdev -type f -printf '%p\n' 2>/dev/null | awk -F/ '{counts[$2]++} END {for (dir in counts) print counts[dir], dir}' | sort -nr | headFor a more direct answer, use du --inodes:
sudo du -x --inodes -d1 /var 2>/dev/null | sort -nHigh inode consumption often comes from many small files in caches, mail spools, session directories, or application-managed temporary directories.
Handle common service startup failures
When a service fails immediately, check the exit status and the last journal entries together:
systemctl status example.service --no-pager -ljournalctl -u example.service -n 100 --no-pagerA missing configuration file often produces a direct error:
example.service: Failed to load configuration files: No such file or directoryCreate or correct the referenced path, then validate the unit:
sudo systemctl daemon-reloadsudo systemctl start example.servicesystemctl status example.service --no-pagerA permission error on a Unix socket is often caused by directory ownership or a restrictive parent directory:
connect() failed (13: Permission denied) while connecting to '/run/example/example.sock'Inspect the complete path, not only the socket:
namei -l /run/example/example.sockls -ld /run /run/examplels -l /run/example/example.sockA missing shared library produces a loader error:
error while loading shared libraries: libexample.so.2: cannot open shared object fileInspect the executable’s dynamic dependencies:
ldd /usr/local/bin/example | grep "not found"If the library exists outside the loader search path, configure the dynamic linker rather than copying the library into an arbitrary system directory:
echo "/opt/example/lib" | sudo tee /etc/ld.so.conf.d/example.confsudo ldconfigThen confirm that the executable and service unit agree on the expected library and environment.
Protect production systems with safer command habits
Administrative work becomes easier to review when commands are non-interactive, idempotent, and explicit about scope. Use systemctl rather than starting daemons directly, because the service manager controls ordering, restart policy, logs, and runtime state.
For scripts, set strict shell behavior when it suits the script:
#!/usr/bin/env bashset -Eeuo pipefailIFS=$'\n\t'Treat unset variables and failed commands as errors. Quote path expansions so spaces or wildcard characters do not split arguments:
cp, "$source_file" "$destination_file"Use temporary files and mktemp instead of predictable paths in /tmp:
workdir=$(mktemp -d)trap 'rm -rf "$workdir"' EXITBefore recursive changes, print the resolved target:
target=$(realpath, "$1")printf 'Target: %s\n' "$target"A production script should also check required privileges, free disk space, service state, and expected file ownership before it begins. Avoid combining unrelated cleanup commands in a single shell line because it becomes difficult to tell which step caused a failure.
Build a practical troubleshooting sequence
A repeatable sequence prevents random command execution. First, confirm the reported symptom and its exact timestamp. Next, check host capacity with df, free, uptime, and iostat. Then inspect the affected service with systemctl status and read the related journal entries.
After that, verify dependencies such as DNS, routing, listening sockets, certificates, and mounted filesystems. Inspect process-level evidence with ps, pidstat, lsof, and strace when permitted. Apply the smallest reversible change, repeat the original check, and record the result.
For network access problems, work from the application outward:
getent hosts example.comdig example.com Aip route get 203.0.113.10nc -vz example.com 443curl -v --connect-timeout 5 https://example.comFor storage problems, work from the mount inward:
findmnt -T /path/to/application/datadf -hT /path/to/application/datadf -ih /path/to/application/datasudo dmesg -T | grep -Ei "I/O error|blk_update|ext4|xfs|nvme|ata"For a suspected hung process, inspect its state and wait channel before sending a signal:
ps -o pid,ppid,stat,wchan:32,etime,cmd -p 1234sudo cat /proc/1234/stacksudo cat /proc/1234/wchanAn uninterruptible sleep is often reported by tools as a hung process, but a kernel-level I/O wait may not respond to SIGTERM until the blocking operation returns. Check storage health and kernel logs before escalating to SIGKILL.
Monitor changes with logs and service metadata
The final diagnosis should include the reason for the change, the commands and configuration used, the validation performed, and any rollback instructions. Journal entries help during the incident, while an operational record helps the next administrator understand why the system differs from its original configuration.
For scheduled tasks, use the scheduler’s own logging instead of relying on a general-purpose wrapper. A cron job that sends output through mail can fail silently when no mail transport is installed. Redirect both output streams to a dedicated log and rotate it:
*/10 * * * * /usr/local/bin/check-service >> /var/log/check-service.log 2>&1For systemd timers, inspect the timer and service separately:
systemctl list-timers --allsystemctl status example.timer --no-pagerjournalctl -u example.service --since todayAvoid creating both a cron entry and a systemd timer for the same task unless both are intentional. Duplicate execution creates misleading logs and can produce concurrent writes.
Use the command line consistently across administration work
The Linux command line remains useful because it exposes system state directly, works over SSH, and can be turned into repeatable scripts. Commands such as ps, ss, lsof, journalctl, df, du, iostat, ip, dig, curl, and systemctl cover much of routine system administration. Their value comes from combining them in a fixed order rather than memorizing isolated flags.
For recurring incidents, save the working command sequence in a runbook. Include the expected output, known error messages, rollback steps, and the conditions that require escalation. That turns a one-time shell session into a repeatable diagnostic procedure for the next operator.