Skip to content
masdzub.com
~/articles/linux — one from the notebook

Mastering the Linux Command Line: Essential Tools for System Administrators

Learn practical Linux command-line tools for monitoring processes, managing storage, inspecting networks, and troubleshooting Linux systems.

masdzub@website:~$ cat ~/articles/mastering-the-linux-command-line-useful-tools-for-sysadmins.aspx.md
# 1 file · 18 min read · topic: linux · status: published

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.

Terminal window
cat /etc/os-release
uname -a
hostnamectl
uptime
who -b

The /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:

Terminal window
test -f /.dockerenv && echo "Docker container"
systemd-detect-virt 2>/dev/null || true
grep -E 'docker|containerd|kubepods' /proc/1/cgroup 2>/dev/null

Create 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.

Terminal window
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>&1

This 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.

Terminal window
ps aux --sort=-%cpu | head -n 15
ps aux --sort=-%mem | head -n 15
ps -eo pid,ppid,user,stat,%cpu,%mem,etime,cmd --sort=-%cpu | head -n 20

The STAT column contains useful state information:

  • R means the process is running or eligible to run.
  • S means it is sleeping and waiting for an event.
  • D means it is waiting on uninterruptible I/O, often a sign of storage or network trouble.
  • Z means the process has terminated but has not been reaped by its parent.
  • T means 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.

Terminal window
iostat -xz 1 5

On Debian and Ubuntu, install the package if needed:

Terminal window
sudo apt-get install sysstat

On RHEL-family systems:

Terminal window
sudo dnf install sysstat

The %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:

Terminal window
pidstat -u -r -d -p ALL 1 10

The -u section reports CPU, -r reports memory, and -d reports disk I/O. Replace ALL with a process ID when the target is known:

Terminal window
pidstat -u -r -d -p 1234 1 10

free clarifies how the kernel is using RAM. Available memory is more useful than the free column because Linux uses otherwise unused RAM for caches.

Terminal window
free -h

Interpret 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:

Terminal window
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:

Terminal window
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.

Terminal window
sudo lsof -p 1234
sudo lsof -i -nP
sudo lsof -iTCP:443 -sTCP:ESTABLISHED

The -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:

Terminal window
ls -l /proc/1234/fd
readlink /proc/1234/fd/* 2>/dev/null

To locate a process using a particular port with tools that are commonly preinstalled:

Terminal window
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:

Terminal window
pstree -aps 1234
systemctl status nginx.service --no-pager
systemctl show nginx.service -p MainPID -p ControlGroup

Follow 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.

Terminal window
journalctl -u nginx.service --since "30 minutes ago"
journalctl -u nginx.service -p warning..alert --since today
journalctl -u nginx.service -f
journalctl -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:

Terminal window
journalctl --list-boots
journalctl -b -1 -u nginx.service
journalctl -b -1 -p err

Use -o short-iso when correlating application events with remote systems. UTC timestamps avoid confusion when servers run in different time zones.

Terminal window
journalctl -u app.service --since today -o short-iso --no-pager

For file-based logs, grep and awk remain useful. Here are two practical examples:

Terminal window
grep -iE "timeout|connection refused|permission denied" /var/log/app.log
awk '$1 == "ERROR" {print strftime("%F %T"), $0}' app.log

Use journalctl --disk-usage before disabling persistent logs. Journal files can consume significant space on hosts with noisy services.

Terminal window
journalctl --disk-usage
sudo journalctl --vacuum-size=500M

The 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.

Terminal window
df -hT
df -ih
sudo du -xhd1 /var 2>/dev/null | sort -h

The -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:

Terminal window
sudo lsof +L1

A 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:

Terminal window
sudo find /var -xdev -type f -size +500M -printf '%s %p\n' 2>/dev/null |
sort -nr | head -n 30

Avoid 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.

Terminal window
lsblk -o NAME,TYPE,SIZE,FSTYPE,FSAVAIL,FSUSE%,MOUNTPOINTS
sudo fdisk -l
sudo parted -l

Use blkid to inspect filesystem labels and UUIDs. UUIDs are safer than device names in persistent configuration because device letters can change between boots.

Terminal window
sudo blkid
ls -l /dev/disk/by-uuid/

The mount table may contain stale entries after a removable disk disappears or a network filesystem fails:

Terminal window
findmnt --verify --verbose
findmnt -t ext4,xfs

A 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:

Terminal window
sudo umount /data
sudo e2fsck -fn /dev/sdb1

The -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:

Terminal window
sudo xfs_repair -n /dev/sdb1

XFS 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:

Terminal window
systemctl status sysstat.service --no-pager
sar -d -s 10:00:00 -e 11:00:00
sar -u ALL 1 10

For network errors and packet counters, use ip and /proc/net/dev:

Terminal window
ip -brief address
ip route
ip -s link
cat /proc/net/dev

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

Terminal window
sudo tcpdump -ni any 'tcp port 443' -w /tmp/https-traffic.pcap

Read the capture on another terminal:

Terminal window
sudo tcpdump -ni any -r /tmp/https-traffic.pcap

Limit 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:

Terminal window
dig example.com A
dig example.com AAAA
dig @1.1.1.1 example.com A
dig example.com MX

A 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:

Terminal window
curl -I --connect-timeout 5 https://example.com
curl -v --connect-timeout 5 https://example.com 2>&1 | head -n 40
openssl s_client -connect example.com:443 -servername example.com </dev/null

Common curl failures have distinct causes:

Could not resolve host: Connection timed out

This 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 server

The 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 certificate

The 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.

Terminal window
systemctl status nginx.service --no-pager -l
systemctl is-enabled nginx.service
systemctl is-active nginx.service

A 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 ago

Read the preceding journal entries instead of restarting immediately:

Terminal window
journalctl -u nginx.service -n 100 --no-pager
journalctl -u nginx.service --since "10 minutes ago" -p warning..alert

Test the unit configuration before restarting:

Terminal window
sudo nginx -t
sudo systemd-analyze verify /etc/systemd/system/example.service

systemd-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:

Terminal window
sudo systemctl daemon-reload
sudo systemctl restart example.service

Changing the unit file does not cause systemd to reread it automatically.

Use systemctl list-units --failed to identify failed units on the host:

Terminal window
systemctl list-units --failed --no-pager

A 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:

Terminal window
sudo nginx -T

The output includes the main configuration and included files. Search it with grep when needed:

Terminal window
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:

Terminal window
sudo apachectl configtest
sudo apachectl -S
sudo apachectlctl -M 2>/dev/null || true

Correct the accidental command above before running it. The valid commands are:

Terminal window
sudo apachectl configtest
sudo apachectl -S
sudo apachectl -M

For HAProxy, systemd manages the process, but the binary can validate its configuration:

Terminal window
sudo haproxy -c -f /etc/haproxy/haproxy.cfg

For Postfix:

Terminal window
sudo postfix check
postconf > /dev/null

For an SSH daemon:

Terminal window
sudo sshd -t
sudo 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 device

Confirm capacity at the exact mount point:

Terminal window
df -h /
df -ih /
findmnt -T /var/log

The 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.

Terminal window
sudo journalctl --vacuum-size=500M
sudo apt-get clean
sudo dnf clean all

Do 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:

Terminal window
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 | head

For a more direct answer, use du --inodes:

Terminal window
sudo du -x --inodes -d1 /var 2>/dev/null | sort -n

High 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:

Terminal window
systemctl status example.service --no-pager -l
journalctl -u example.service -n 100 --no-pager

A missing configuration file often produces a direct error:

example.service: Failed to load configuration files: No such file or directory

Create or correct the referenced path, then validate the unit:

Terminal window
sudo systemctl daemon-reload
sudo systemctl start example.service
systemctl status example.service --no-pager

A 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:

Terminal window
namei -l /run/example/example.sock
ls -ld /run /run/example
ls -l /run/example/example.sock

A missing shared library produces a loader error:

error while loading shared libraries: libexample.so.2: cannot open shared object file

Inspect the executable’s dynamic dependencies:

Terminal window
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:

Terminal window
echo "/opt/example/lib" | sudo tee /etc/ld.so.conf.d/example.conf
sudo ldconfig

Then 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 bash
set -Eeuo pipefail
IFS=$'\n\t'

Treat unset variables and failed commands as errors. Quote path expansions so spaces or wildcard characters do not split arguments:

Terminal window
cp, "$source_file" "$destination_file"

Use temporary files and mktemp instead of predictable paths in /tmp:

Terminal window
workdir=$(mktemp -d)
trap 'rm -rf "$workdir"' EXIT

Before recursive changes, print the resolved target:

Terminal window
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:

Terminal window
getent hosts example.com
dig example.com A
ip route get 203.0.113.10
nc -vz example.com 443
curl -v --connect-timeout 5 https://example.com

For storage problems, work from the mount inward:

Terminal window
findmnt -T /path/to/application/data
df -hT /path/to/application/data
df -ih /path/to/application/data
sudo 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:

Terminal window
ps -o pid,ppid,stat,wchan:32,etime,cmd -p 1234
sudo cat /proc/1234/stack
sudo cat /proc/1234/wchan

An 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>&1

For systemd timers, inspect the timer and service separately:

Terminal window
systemctl list-timers --all
systemctl status example.timer --no-pager
journalctl -u example.service --since today

Avoid 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.

found this useful? share it →
Written by

Dzubayyan Ahmad

System Administrator, SRE & Technical Support Engineer specialising in web hosting infrastructure — Linux servers, automation, and monitoring. Writing these notes since 2015 so future-me can find the fix again.