Linux Command Cheat Sheet

Comprehensive Linux command reference covering navigation, files, text processing, permissions, processes, system information, networking, archives, services, storage, and troubleshooting.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all

Files and Directories

Create, copy, move, inspect, and delete filesystem objects.

Create file or update timestamp

Create an empty file if it does not exist.

bashLINUXtouchfile
bash
touch notes.txt

Also updates the modification time of an existing file.

Create nested directories

Create one or more directories, including parents.

bashLINUXmkdirdirectory
bash
mkdir -p app/logs/archive

`-p` prevents errors if parent directories are missing.

Copy files recursively

Copy files or directories.

bashLINUXcpcopyfilesystem
bash
cp -av src/ backup/src/

`-a` preserves attributes and recursion, `-v` shows progress.

Move or rename file

Move or rename a file or directory.

bashLINUXmvrenamefilesystem
bash
mv old-name.txt new-name.txt

Also used to move files between directories.

Remove file

Delete a file.

bashLINUXrmdeletefilesystem
bash
rm file.txt

Double-check with `ls` first when deleting important files.

Remove directory recursively

Delete a directory tree forcefully.

bashLINUXrmdeletedanger
bash
rm -rf build/

Dangerous. Verify the path carefully before running.

Remove empty directory

Delete an empty directory.

bashLINUXrmdirdirectory
bash
rmdir empty-dir

Fails if the directory contains files.

Create symbolic link

Create a symlink that points to another path.

bashLINUXlnsymlinkfilesystem
bash
ln -s /opt/app/current app-current

Symlinks are useful for release switching, shared config, and path aliases.

Create hard link

Create an additional directory entry for the same inode.

bashLINUXlnhardlinkinode
bash
ln original.txt twin.txt

Hard links only work on the same filesystem and usually not for directories.

Show file metadata

Display inode, permissions, timestamps, and size.

bashLINUXstatmetadatafilesystem
bash
stat /var/log/syslog

Excellent for debugging permissions, timestamps, and file identity.

Detect file type

Identify file contents and encoding.

bashLINUXfileinspectionformat
bash
file archive.tar.gz

Useful when an extension is misleading or absent.

Show disk usage by path

Estimate file and directory sizes.

bashLINUXdudiskusage
bash
du -sh *

Useful for quickly finding which directories consume the most space.

Show filesystem free space

Display mounted filesystems and free space.

bashLINUXdfdiskfilesystem
bash
df -h

Use this before large downloads, backups, or container/image pulls.

Strip directory and suffix from path

Return the last path component.

bashLINUXbasenamepathshell
bash
basename /var/log/nginx/access.log .log

Helpful in shell scripting and loops.

Get directory portion of path

Return the parent directory of a path.

bashLINUXdirnamepathshell
bash
dirname /var/log/nginx/access.log

Common in scripts that need to construct sibling paths.

Viewing and Text Basics

Read files, inspect content, and work with text streams.

Print file contents

Concatenate and print files to standard output.

bashLINUXcattextfiles
bash
cat /etc/os-release

Good for small files and quick checks.

Page through a file

Open a file in a scrollable pager.

bashLINUXlesspagerlogs
bash
less /var/log/syslog

Search inside `less` with `/pattern` and quit with `q`.

Show last lines

Display the end of a file.

bashLINUXtaillogstext
bash
tail -n 50 app.log

Often used on logs to inspect the latest events.

Follow a growing file

Stream appended lines as they are written.

bashLINUXtailfollowlogs
bash
tail -f /var/log/nginx/access.log

Classic log-following pattern while a service is running.

Count lines words and bytes

Count content in files or streams.

bashLINUXwccounttext
bash
wc -l users.csv

Great for line counts in logs, CSVs, or batch outputs.

Number lines

Display file contents with line numbers.

bashLINUXnltextlines
bash
nl -ba config.yml

Useful when discussing exact lines in reviews or incidents.

Select fields from lines

Extract portions of each line.

bashLINUXcutfieldstext
bash
cut -d: -f1 /etc/passwd

A staple for colon-, comma-, or tab-delimited data.

Merge lines side-by-side

Combine files line-by-line.

bashLINUXpastemergetext
bash
paste names.txt emails.txt

Useful for quick column composition without opening a spreadsheet.

Pretty-print columns

Format delimited text into aligned columns.

bashLINUXcolumnformattext
bash
column -t -s, data.csv

Helpful for inspecting CSV-like data in the terminal.

Sort lines

Sort input lines lexicographically or numerically.

bashLINUXsorttextprocessing
bash
sort -t, -k2,2n scores.csv

Combine with `uniq`, `comm`, or `join` for powerful text workflows.

Filter duplicate adjacent lines

Collapse repeated adjacent lines.

bashLINUXuniqdedupetext
bash
sort access.log | uniq -c | sort -nr

Remember to sort first if you want global duplicate counts.

Translate or delete characters

Replace or delete characters from a stream.

bashLINUXtrtransformtext
bash
tr '[:lower:]' '[:upper:]' < input.txt

Also useful for squeezing repeated delimiters with `-s`.

Write output to file and stdout

Send output to both a file and the terminal.

bashLINUXteeloggingpipes
bash
make 2>&1 | tee build.log

Great for preserving command output while still seeing it live.

Searching and Pattern Matching

Search text, files, directories, and command history efficiently.

Search text with grep

Print lines matching a pattern.

bashLINUXgrepsearchtext
bash
grep -n 'ERROR' app.log

`-n` adds line numbers. Add `-i` for case-insensitive searches.

Search recursively under a directory

Search all matching files in a tree.

bashLINUXgreprecursivecode
bash
grep -RIn 'TODO' src/

A standard codebase search when ripgrep is unavailable.

Show non-matching lines

Exclude lines that match a pattern.

bashLINUXgrepinvertfilter
bash
grep -v '^#' .env.example

Useful for stripping comments or blank lines when combined with other filters.

Extended regex search

Use extended regular expressions with grep.

bashLINUXgrepregexsearch
bash
grep -E 'warn|error|fatal' app.log

Equivalent to historical `egrep`; `grep -E` is preferred.

Fixed-string search

Match text literally instead of as a regex.

bashLINUXgrepfixed-stringsearch
bash
grep -F 'user[id]' app.log

Use when the pattern contains regex metacharacters you want treated literally.

Fast recursive search with rg

Recursively search text quickly while respecting ignore rules.

bashLINUXrgripgrepsearch
bash
rg 'connection refused' .

Popular for source-code and repo searches due to speed and sane defaults.

Find files by modification time

Search for files changed recently.

bashLINUXfindmtimesearch
bash
find /var/log -type f -mtime -1

Helpful for cleanup jobs and recent-activity investigations.

Find files by size

Locate large files with size filters.

bashLINUXfindsizedisk
bash
find / -type f -size +500M 2>/dev/null

Useful in disk pressure incidents.

Build command lines from stdin

Pass stdin items as arguments to another command.

bashLINUXxargsbulkshell
bash
find . -name '*.tmp' -print0 | xargs -0 rm -f

Essential when combining `find` with bulk operations safely.

Search shell history

Filter previous shell commands.

bashLINUXhistorysearchshell
bash
history | grep docker

A good way to recover a command you ran last week but forgot to save.

Permissions Ownership and ACLs

Manage modes, ownership, access, and identity.

List permissions

Show permissions and ownership on files.

bashLINUXpermissionsownershipls
bash
ls -l /var/www

The first step in diagnosing file access problems.

Change permissions with numeric mode

Set rwx permissions numerically.

bashLINUXchmodpermissions
bash
chmod 640 secrets.env

Numeric modes are concise and script-friendly.

Change permissions recursively

Apply a mode to a directory tree.

bashLINUXchmodrecursivepermissions
bash
chmod -R u=rwX,go=rX public/

Prefer symbolic recursive modes for directories so execute is only set where appropriate.

Change owner and group

Set file owner and group.

bashLINUXchownownership
bash
chown deploy:www-data app.log

Common after copying files as root or changing deployment users.

Change group owner

Set the group of a file or directory.

bashLINUXchgrpgroupownership
bash
chgrp www-data storage/

Useful when a shared service account needs group access.

Show or set default permission mask

Control default modes for new files and directories.

bashLINUXumaskpermissionsdefaults
bash
umask 027

A stricter umask helps keep new files from being world-readable.

Show current user and groups

Display numeric and named identity info.

bashLINUXididentityuser
bash
id

Quickly confirms which groups a process or login shell belongs to.

Print current username

Show the effective user name.

bashLINUXuseridentity
bash
whoami

Handy in `sudo` sessions and provisioning scripts.

Show ACLs

Inspect Access Control Lists on a file or directory.

bashLINUXaclpermissionsgetfacl
bash
getfacl shared/

Useful when POSIX ACLs override or supplement traditional mode bits.

Set ACL entries

Grant or modify fine-grained access rules.

bashLINUXaclpermissionssetfacl
bash
setfacl -m u:alice:rwx shared/

Helpful when one extra user needs access without changing ownership.

Run command as root

Execute a command with elevated privileges.

bashLINUXsudoprivilegeadmin
bash
sudo systemctl restart nginx

Keep privilege escalation narrow and targeted.

Edit protected file safely

Open a file for editing through sudo.

bashLINUXsudoeditsecurity
bash
sudoedit /etc/ssh/sshd_config

Safer than running the editor as root directly.

Users Groups and Sessions

Create users, manage groups, inspect sessions, and handle logins.

Create a user

Create a new local user account.

bashLINUXuseraccountadmin
bash
sudo useradd -m -s /bin/bash deploy

`-m` creates the home directory and `-s` sets the login shell.

Add user to supplementary group

Append a user to an extra group.

bashLINUXusergroupadmin
bash
sudo usermod -aG docker alice

Always include `-a` with `-G` to avoid overwriting existing supplementary groups.

Set or change password

Set a local user password.

bashLINUXpassworduseradmin
bash
sudo passwd deploy

Also used to lock and unlock passwords on many systems.

Create a group

Add a new local group.

bashLINUXgroupadmin
bash
sudo groupadd appteam

Useful for shared file access patterns.

List groups for a user

Show supplementary group membership.

bashLINUXgroupsuseridentity
bash
groups alice

Useful when access depends on group membership.

Switch user with login shell

Become another user and load their shell profile.

bashLINUXsuusershell
bash
su - postgres

Classic for service accounts that own app data or databases.

Show logged in users

List active login sessions.

bashLINUXwhosessionsuser
bash
who

Helpful on shared servers and bastion hosts.

Show logged in users and activity

Display users plus current processes and load.

bashLINUXwsessionsops
bash
w

A quick operations view of who is on the machine and what they are doing.

Show login history

Display recent login records.

bashLINUXlasthistorysecurity
bash
last -a | head

Useful for forensic review and access audits.

Kill all processes for a user

Terminate processes owned by a specific user.

bashLINUXpkilluserprocess
bash
sudo pkill -u olddeploy

Use carefully on multi-user systems.

Processes Jobs and Scheduling

Inspect, prioritize, signal, background, and schedule processes.

List processes

Show running processes in BSD format.

bashLINUXpsprocessinspection
bash
ps aux

One of the most common process-inspection commands.

Show process tree

Display processes in a parent-child tree.

bashLINUXpsprocess-treeinspection
bash
ps -ef --forest

Helpful for understanding supervisors, workers, and spawned shells.

Interactive process viewer

Monitor processes, CPU, and memory interactively.

bashLINUXtopprocesscpu
bash
top

Built into most systems and good for quick diagnostics.

Interactive process viewer with UI

Use a richer interactive process monitor.

bashLINUXhtopprocessmemory
bash
htop

Friendlier than `top` if installed.

Find process IDs by name

Search for process IDs using a pattern.

bashLINUXpgrepprocesssearch
bash
pgrep -af nginx

Great for scripts and quick service discovery.

Send TERM signal

Request graceful process termination.

bashLINUXkillsignalprocess
bash
kill -TERM 12345

Prefer TERM before KILL so apps can shut down cleanly.

Force kill process

Send SIGKILL to stop a process immediately.

bashLINUXkillsignaldanger
bash
kill -KILL 12345

Use only when a process ignores or cannot handle graceful signals.

Kill processes by pattern

Signal processes matching a name or regex.

bashLINUXpkillsignalprocess
bash
pkill -f 'gunicorn: master'

Convenient when you do not want to look up PIDs manually.

Start process with adjusted priority

Run a command at a different CPU scheduling priority.

bashLINUXnicepriorityprocess
bash
nice -n 10 tar -czf backup.tgz /srv/data

Higher nice values are lower priority.

Change running process priority

Adjust niceness of an existing process.

bashLINUXrenicepriorityprocess
bash
sudo renice -n 5 -p 12345

Useful when a process should yield more CPU to others.

List shell jobs

Show background and stopped jobs for the current shell.

bashLINUXjobsshellbackground
bash
jobs -l

Only applies to jobs started from the same shell session.

Resume stopped job in background

Continue a suspended job in the background.

bashLINUXbgjobsshell
bash
bg %1

Useful after pressing Ctrl+Z on a long-running command.

Bring job to foreground

Resume a background or stopped job in the foreground.

bashLINUXfgjobsshell
bash
fg %1

Useful when you need to interact with the command again.

Keep process running after logout

Run a command immune to hangups.

bashLINUXnohupbackgroundshell
bash
nohup ./long-task.sh > task.out 2>&1 &

Useful on remote shells when a process should survive disconnects.

Edit user crontab

Create or modify scheduled tasks.

bashLINUXcronschedulecrontab
bash
crontab -e

Classic recurring scheduler for scripts, backups, and maintenance tasks.

List user crontab

Show scheduled cron entries.

bashLINUXcronschedulecrontab
bash
crontab -l

Useful before changing automation on a server.

Schedule one-time job

Queue a command to run once later.

bashLINUXatschedulejobs
bash
echo 'systemctl restart worker' | at 02:00

Useful for maintenance actions that should run once at a known time.

System Information and Hardware

Inspect OS details, CPU, memory, uptime, devices, and kernel state.

Show kernel and system info

Print kernel and architecture details.

bashLINUXunamekernelsystem
bash
uname -a

Common first step to see what OS and kernel you are on.

Show or set hostname

Inspect hostname, OS, and virtualization metadata.

bashLINUXhostnamectlsystemdsystem
bash
hostnamectl

On systemd systems this is richer than plain `hostname`.

Show distribution info

Print distribution metadata from os-release.

bashLINUXdistroos-releasesystem
bash
cat /etc/os-release

Portable way to detect distro family in scripts or debugging.

Show uptime and load

Print system uptime and load averages.

bashLINUXuptimeloadsystem
bash
uptime

Useful during incidents and after reboots.

Show memory usage

Display RAM and swap usage.

bashLINUXmemoryfreesystem
bash
free -h

Commonly used alongside `top`, `ps`, and `vmstat`.

Show CPU information

Display CPU architecture and core details.

bashLINUXcpuhardwaresystem
bash
lscpu

Useful for capacity planning and debugging architecture issues.

List block devices

Show disks, partitions, and mountpoints.

bashLINUXstorageblocksystem
bash
lsblk -f

Excellent for storage troubleshooting and identifying filesystems.

Show block device UUIDs

Display filesystem type and UUID labels.

bashLINUXstorageuuidfilesystem
bash
sudo blkid

Often used when preparing `/etc/fstab` entries.

Show or mount filesystems

List mounted filesystems or mount one manually.

bashLINUXmountfilesystemstorage
bash
mount | column -t

Useful to inspect what is currently mounted and with which options.

Unmount a filesystem

Detach a mounted filesystem.

bashLINUXumountfilesystemstorage
bash
sudo umount /mnt/data

Always ensure no process is using the mount before unmounting.

Show kernel ring buffer

Inspect kernel messages and boot-time hardware logs.

bashLINUXdmesgkernellogs
bash
dmesg -T | tail -n 50

Great for device, disk, driver, and OOM-related debugging.

List USB devices

Display connected USB hardware.

bashLINUXusbhardwaredevices
bash
lsusb

Useful for debugging peripherals, storage, serial, and dev boards.

List PCI devices

Display PCI and PCIe hardware.

bashLINUXpcihardwaredevices
bash
lspci -nn

Useful for graphics, NIC, NVMe, and virtualization inspection.

Networking and Remote Access

Inspect interfaces, routes, connections, DNS, and remote connectivity.

Show IP addresses

Display interfaces and assigned addresses.

bashLINUXipnetworkaddress
bash
ip address show

Modern replacement for `ifconfig` on most Linux systems.

Show routing table

Display current IP routes.

bashLINUXiproutenetwork
bash
ip route show

Essential when debugging egress paths and default gateways.

List listening sockets

Show listening TCP and UDP ports with processes.

bashLINUXssportsnetwork
bash
ss -tulpn

Modern replacement for `netstat -tulpn` on many systems.

Test basic reachability

Send ICMP echo requests to a host.

bashLINUXpingnetworkreachability
bash
ping -c 4 8.8.8.8

Good first test for network reachability and latency.

Trace network path

Display the route packets take to a host.

bashLINUXtraceroutenetworkrouting
bash
traceroute example.com

Useful for diagnosing where connectivity breaks across hops.

Query DNS records

Look up DNS answers directly.

bashLINUXdnsdignetwork
bash
dig +short A example.com

Preferred over older tools for precise DNS debugging.

Basic DNS lookup

Query DNS information interactively or directly.

bashLINUXdnsnslookupnetwork
bash
nslookup example.com

Still common, though `dig` is often more scriptable and explicit.

Simple DNS lookup

Resolve names or reverse-lookup addresses.

bashLINUXdnshostnetwork
bash
host 8.8.8.8

Quick and minimal DNS utility.

Transfer data with URLs

Make HTTP requests and API calls.

bashLINUXcurlhttpapi
bash
curl -I https://example.com

Great for headers, health checks, APIs, and downloads.

Download files over HTTP FTP

Retrieve files non-interactively.

bashLINUXwgetdownloadnetwork
bash
wget https://example.com/file.tar.gz

Useful for unattended downloads and mirroring.

Open remote shell

Connect securely to another host.

bashLINUXsshremoteshell
bash
ssh user@server.example.com

A core Linux skill for administration and deployments.

Copy files over SSH

Transfer files between hosts securely.

bashLINUXscpsshcopy
bash
scp app.tar.gz user@server:/tmp/

Simple and widely available for secure file copy.

Synchronize files over SSH

Copy files efficiently with deltas and preservation.

bashLINUXrsyncsshsync
bash
rsync -avz ./dist/ user@server:/var/www/app/

A deployment and backup staple thanks to speed and repeatability.

Open TCP or UDP connections

Use netcat for port checks and simple listeners.

bashLINUXncnetcatnetwork
bash
nc -vz example.com 443

Excellent for quick TCP connectivity tests.

Scan ports and services

Probe a host for open ports and services.

bashLINUXnmapportsnetwork
bash
nmap -sV example.com

Use responsibly and only on systems you are authorized to scan.

Capture packets

Inspect network traffic from the command line.

bashLINUXtcpdumppacketsnetwork
bash
sudo tcpdump -i any port 443

Powerful for low-level debugging of connections, TLS, DNS, and service issues.

Archives Compression and Checksums

Create archives, compress files, and verify integrity.

Create tar archive

Bundle files into a tar archive.

bashLINUXtararchivebackup
bash
tar -cvf backup.tar app/

Classic archiving tool for backups and packaging.

Create gzip-compressed tarball

Archive and compress in one step.

bashLINUXtargziparchive
bash
tar -czvf backup.tar.gz app/

Common format for source releases and backups.

Extract tarball

Unpack an archive into the current directory.

bashLINUXtarextractarchive
bash
tar -xzvf backup.tar.gz

Add `-C /target/path` to extract elsewhere.

Compress file with gzip

Compress a file and replace it with a `.gz` version.

bashLINUXgzipcompress
bash
gzip large.log

Simple and widely supported compression format.

Decompress gzip file

Expand a `.gz` file back to its original contents.

bashLINUXgzipdecompress
bash
gunzip large.log.gz

Equivalent to `gzip -d`.

Create zip archive

Archive and compress files in zip format.

bashLINUXziparchivecompress
bash
zip -r release.zip dist/

Convenient when sharing with systems that expect zip.

Extract zip archive

Unpack zip files.

bashLINUXzipextract
bash
unzip release.zip -d release/

Simple cross-platform archive extraction.

Compress with xz

Compress a file using xz.

bashLINUXxzcompress
bash
xz -T0 dump.sql

Excellent compression ratios, often used for large text dumps.

Generate SHA-256 checksum

Compute file integrity digest.

bashLINUXchecksumsha256integrity
bash
sha256sum release.tar.gz

Useful for verifying downloads and release artifacts.

Generate MD5 checksum

Compute MD5 digest.

bashLINUXchecksummd5integrity
bash
md5sum file.iso

Mostly used for legacy checks; prefer SHA-256 for stronger integrity assurance.

sed awk and Structured Text Workflows

Edit text streams, transform columns, and script data extraction.

Replace text with sed

Substitute matching text in a stream.

bashLINUXsedreplacetext
bash
sed 's/localhost/db.internal/g' config.tpl

Useful for one-off substitutions in streams or pipelines.

Edit file in place with sed

Modify a file directly.

bashLINUXsedin-placetext
bash
sed -i.bak 's/debug=false/debug=true/' app.conf

Create a backup suffix when editing important files.

Print line range

Show a line range from a file.

bashLINUXsedrangetext
bash
sed -n '100,140p' big.log

Helpful for extracting a specific section without opening an editor.

Print selected columns with awk

Extract columns from whitespace-delimited text.

bashLINUXawkcolumnstext
bash
awk '{print $1, $5}' access.log

Great for quick field extraction and lightweight reporting.

Sum values with awk

Aggregate numeric values from a column.

bashLINUXawksumaggregation
bash
awk '{sum += $3} END {print sum}' metrics.txt

Useful for fast command-line summaries.

Filter rows with awk

Print rows that satisfy a condition.

bashLINUXawkfiltertext
bash
awk '$5 > 100 {print $0}' usage.txt

Useful when conditions go beyond what `grep` handles cleanly.

Pretty-print JSON

Format JSON output for readability.

bashLINUXjqjsonformat
bash
jq '.' response.json

A must-have when APIs or tools emit raw JSON.

Extract JSON field

Read a nested field from JSON.

bashLINUXjqjsonextract
bash
jq -r '.items[].metadata.name' pods.json

Excellent for combining API JSON with shell pipelines.

Read YAML field

Extract data from YAML.

bashLINUXyqyamlextract
bash
yq '.services.web.image' docker-compose.yml

Useful for Kubernetes, Compose, CI, and config files.

Compare sorted files line-by-line

Show lines unique to each file or common to both.

bashLINUXcommcomparetext
bash
comm -3 <(sort old.txt) <(sort new.txt)

Handy for diffing identifier lists and inventory files.

Join two files on a common field

Relational join for sorted text files.

bashLINUXjointextdata
bash
join -1 1 -2 1 users.txt emails.txt

Useful when doing small-scale data joins in shell pipelines.

Split file into chunks

Break a file into smaller pieces.

bashLINUXsplitfilebatch
bash
split -l 100000 huge.csv chunk_

Helpful for batch imports or sharing giant files.

Services systemd and Journal

Manage services, units, boot targets, and logs on systemd hosts.

Show service status

Display service state and recent log snippets.

bashLINUXsystemctlservicestatus
bash
systemctl status nginx

A first-stop diagnostic for any systemd-managed service.

Start service

Start a service immediately.

bashLINUXsystemctlservicestart
bash
sudo systemctl start nginx

Use after install or when recovering a stopped service.

Stop service

Stop a running service.

bashLINUXsystemctlservicestop
bash
sudo systemctl stop nginx

Use before maintenance or configuration changes when needed.

Restart service

Restart a service cleanly.

bashLINUXsystemctlservicerestart
bash
sudo systemctl restart nginx

Common after config changes or deployments.

Reload service config

Ask a service to reload configuration without full restart.

bashLINUXsystemctlservicereload
bash
sudo systemctl reload nginx

Prefer reload when the service supports it and you want minimal disruption.

Enable service on boot

Create boot-time activation links for a unit.

bashLINUXsystemctlserviceboot
bash
sudo systemctl enable nginx

Ensures the service starts automatically after reboot.

Disable service on boot

Remove boot-time activation for a unit.

bashLINUXsystemctlserviceboot
bash
sudo systemctl disable nginx

Useful for deprecated or temporary services.

List loaded units

Show active units known to systemd.

bashLINUXsystemctlunitsservice
bash
systemctl list-units --type=service

Useful for discovering services and their current states.

View logs for a service

Show journal entries for a specific systemd unit.

bashLINUXjournalctllogsservice
bash
journalctl -u nginx -n 100 --no-pager

A standard service-specific log query on systemd systems.

Follow journal logs

Stream new journal entries live.

bashLINUXjournalctllogsfollow
bash
journalctl -fu nginx

Combines `-f` follow mode with unit filtering.

Show logs from current boot

Query logs for the active boot session.

bashLINUXjournalctlbootlogs
bash
journalctl -b

Use `-b -1` to inspect the previous boot.

Inspect time and timezone settings

Show or change system clock, timezone, and NTP status.

bashLINUXtimetimezonesystemd
bash
timedatectl

Important when debugging clock drift, certificates, or scheduled tasks.

Set hostname with systemd

Change the system hostname.

bashLINUXhostnamectlhostnamesystemd
bash
sudo hostnamectl set-hostname app-prod-01

Preferred over editing files manually on systemd systems.

Storage Partitions and LVM

Work with disks, partitions, filesystems, and logical volumes.

List partition tables

Show partitions on available disks.

bashLINUXfdiskpartitionsstorage
bash
sudo fdisk -l

Classic disk inventory command.

Print partition layout

Inspect partitions with GNU Parted.

bashLINUXpartedpartitionsstorage
bash
sudo parted /dev/sda print

Useful for modern disks and scripted partition management.

Create ext4 filesystem

Format a block device with ext4.

bashLINUXmkfsext4filesystem
bash
sudo mkfs.ext4 /dev/sdb1

Formatting destroys existing data; verify the target device carefully.

Check filesystem

Check and repair a filesystem.

bashLINUXfsckrepairfilesystem
bash
sudo fsck -f /dev/sdb1

Run on unmounted filesystems when possible.

Mount device to path

Attach a filesystem to a mountpoint.

bashLINUXmountstoragefilesystem
bash
sudo mount /dev/sdb1 /mnt/data

Ensure the mountpoint exists first.

Enable swap device or file

Activate swap space.

bashLINUXswapmemorystorage
bash
sudo swapon /swapfile

Useful when adding or restoring swap.

Disable swap device or file

Turn off swap usage.

bashLINUXswapmemorystorage
bash
sudo swapoff /swapfile

Ensure the system has enough RAM before disabling swap.

List physical volumes

Show LVM physical volumes.

bashLINUXlvmstoragepvs
bash
sudo pvs

Start here when inspecting LVM-backed systems.

List volume groups

Show LVM volume groups.

bashLINUXlvmstoragevgs
bash
sudo vgs

Useful for capacity and free-extent checks.

List logical volumes

Show LVM logical volumes.

bashLINUXlvmstoragelvs
bash
sudo lvs

Useful for seeing LV names, sizes, and attributes.

Extend logical volume

Increase logical volume size.

bashLINUXlvmresizestorage
bash
sudo lvextend -L +20G /dev/vg0/data

Often followed by filesystem growth with `resize2fs` or `xfs_growfs`.

Grow ext filesystem

Resize an ext2/3/4 filesystem after volume growth.

bashLINUXfilesystemresizeext4
bash
sudo resize2fs /dev/vg0/data

Common after extending an LV or block device.

Performance Monitoring and Troubleshooting

Gather CPU, memory, IO, and process diagnostics during incidents.

Show virtual memory stats

Display system activity, processes, memory, and IO over time.

bashLINUXvmstatperformancememory
bash
vmstat 1 5

A compact snapshot for system pressure and waiting behavior.

Show CPU and disk IO stats

Report CPU utilization and block-device performance.

bashLINUXiostatdiskperformance
bash
iostat -xz 1 5

Useful for diagnosing disk saturation and queue depth.

Collect and report system activity

Use sysstat historical metrics.

bashLINUXsarperformancehistory
bash
sar -u 1 5

Great when sysstat is installed and enabled for ongoing collection.

Show per-CPU stats

Display CPU usage by processor.

bashLINUXmpstatcpuperformance
bash
mpstat -P ALL 1 5

Useful when one core is pegged but system average looks fine.

Show per-process stats

Report CPU, memory, and IO by process.

bashLINUXpidstatprocessperformance
bash
pidstat 1 5

Helps connect system pressure to specific workloads.

List open files

Show files and sockets opened by processes.

bashLINUXlsoffilesports
bash
lsof -i :8080

Excellent for determining what process owns a port or file.

Trace system calls

Inspect syscalls made by a process or command.

bashLINUXstracedebugsyscalls
bash
strace -p 12345

Powerful for seeing what a stuck or failing process is trying to do.

Measure command runtime

Report elapsed user and system time for a command.

bashLINUXtimebenchmarkshell
bash
time rsync -av src/ backup/

Useful for baseline timing and quick performance comparison.

Run a command repeatedly

Refresh output at an interval.

bashLINUXwatchmonitoringshell
bash
watch -n 2 'df -h && echo && free -h'

Great for observing changing state without rerunning commands manually.

Limit runtime of command

Stop a command after a maximum duration.

bashLINUXtimeoutshellcontrol
bash
timeout 30s curl -I https://example.com

Useful in scripts to avoid hanging forever.