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
Notes

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
Notes

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

Copy files recursively

Copy files or directories.

bashLINUXcpcopyfilesystem
bash
cp -av src/ backup/src/
Notes

`-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
Notes

Also used to move files between directories.

Remove file

Delete a file.

bashLINUXrmdeletefilesystem
bash
rm file.txt
Notes

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

Remove directory recursively

Delete a directory tree forcefully.

bashLINUXrmdeletedanger
bash
rm -rf build/
Notes

Dangerous. Verify the path carefully before running.

Remove empty directory

Delete an empty directory.

bashLINUXrmdirdirectory
bash
rmdir empty-dir
Notes

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
Notes

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
Notes

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
Notes

Excellent for debugging permissions, timestamps, and file identity.

Detect file type

Identify file contents and encoding.

bashLINUXfileinspectionformat
bash
file archive.tar.gz
Notes

Useful when an extension is misleading or absent.

Show disk usage by path

Estimate file and directory sizes.

bashLINUXdudiskusage
bash
du -sh *
Notes

Useful for quickly finding which directories consume the most space.

Show filesystem free space

Display mounted filesystems and free space.

bashLINUXdfdiskfilesystem
bash
df -h
Notes

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
Notes

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
Notes

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
Notes

Good for small files and quick checks.

Page through a file

Open a file in a scrollable pager.

bashLINUXlesspagerlogs
bash
less /var/log/syslog
Notes

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
Notes

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
Notes

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
Notes

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

Number lines

Display file contents with line numbers.

bashLINUXnltextlines
bash
nl -ba config.yml
Notes

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
Notes

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
Notes

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
Notes

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
Notes

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
Notes

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
Notes

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
Notes

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
Notes

`-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/
Notes

A standard codebase search when ripgrep is unavailable.

Show non-matching lines

Exclude lines that match a pattern.

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

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
Notes

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
Notes

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' .
Notes

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
Notes

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
Notes

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
Notes

Essential when combining `find` with bulk operations safely.

Search shell history

Filter previous shell commands.

bashLINUXhistorysearchshell
bash
history | grep docker
Notes

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
Notes

The first step in diagnosing file access problems.

Change permissions with numeric mode

Set rwx permissions numerically.

bashLINUXchmodpermissions
bash
chmod 640 secrets.env
Notes

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/
Notes

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
Notes

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/
Notes

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
Notes

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
Notes

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

Print current username

Show the effective user name.

bashLINUXuseridentity
bash
whoami
Notes

Handy in `sudo` sessions and provisioning scripts.

Show ACLs

Inspect Access Control Lists on a file or directory.

bashLINUXaclpermissionsgetfacl
bash
getfacl shared/
Notes

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/
Notes

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
Notes

Keep privilege escalation narrow and targeted.

Edit protected file safely

Open a file for editing through sudo.

bashLINUXsudoeditsecurity
bash
sudoedit /etc/ssh/sshd_config
Notes

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
Notes

`-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
Notes

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
Notes

Also used to lock and unlock passwords on many systems.

Create a group

Add a new local group.

bashLINUXgroupadmin
bash
sudo groupadd appteam
Notes

Useful for shared file access patterns.

List groups for a user

Show supplementary group membership.

bashLINUXgroupsuseridentity
bash
groups alice
Notes

Useful when access depends on group membership.

Switch user with login shell

Become another user and load their shell profile.

bashLINUXsuusershell
bash
su - postgres
Notes

Classic for service accounts that own app data or databases.

Show logged in users

List active login sessions.

bashLINUXwhosessionsuser
bash
who
Notes

Helpful on shared servers and bastion hosts.

Show logged in users and activity

Display users plus current processes and load.

bashLINUXwsessionsops
bash
w
Notes

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
Notes

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
Notes

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
Notes

One of the most common process-inspection commands.

Show process tree

Display processes in a parent-child tree.

bashLINUXpsprocess-treeinspection
bash
ps -ef --forest
Notes

Helpful for understanding supervisors, workers, and spawned shells.

Interactive process viewer

Monitor processes, CPU, and memory interactively.

bashLINUXtopprocesscpu
bash
top
Notes

Built into most systems and good for quick diagnostics.

Interactive process viewer with UI

Use a richer interactive process monitor.

bashLINUXhtopprocessmemory
bash
htop
Notes

Friendlier than `top` if installed.

Find process IDs by name

Search for process IDs using a pattern.

bashLINUXpgrepprocesssearch
bash
pgrep -af nginx
Notes

Great for scripts and quick service discovery.

Send TERM signal

Request graceful process termination.

bashLINUXkillsignalprocess
bash
kill -TERM 12345
Notes

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
Notes

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'
Notes

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
Notes

Higher nice values are lower priority.

Change running process priority

Adjust niceness of an existing process.

bashLINUXrenicepriorityprocess
bash
sudo renice -n 5 -p 12345
Notes

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
Notes

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
Notes

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
Notes

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 &
Notes

Useful on remote shells when a process should survive disconnects.

Edit user crontab

Create or modify scheduled tasks.

bashLINUXcronschedulecrontab
bash
crontab -e
Notes

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

List user crontab

Show scheduled cron entries.

bashLINUXcronschedulecrontab
bash
crontab -l
Notes

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
Notes

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
Notes

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
Notes

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
Notes

Portable way to detect distro family in scripts or debugging.

Show uptime and load

Print system uptime and load averages.

bashLINUXuptimeloadsystem
bash
uptime
Notes

Useful during incidents and after reboots.

Show memory usage

Display RAM and swap usage.

bashLINUXmemoryfreesystem
bash
free -h
Notes

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

Show CPU information

Display CPU architecture and core details.

bashLINUXcpuhardwaresystem
bash
lscpu
Notes

Useful for capacity planning and debugging architecture issues.

List block devices

Show disks, partitions, and mountpoints.

bashLINUXstorageblocksystem
bash
lsblk -f
Notes

Excellent for storage troubleshooting and identifying filesystems.

Show block device UUIDs

Display filesystem type and UUID labels.

bashLINUXstorageuuidfilesystem
bash
sudo blkid
Notes

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

Show or mount filesystems

List mounted filesystems or mount one manually.

bashLINUXmountfilesystemstorage
bash
mount | column -t
Notes

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

Unmount a filesystem

Detach a mounted filesystem.

bashLINUXumountfilesystemstorage
bash
sudo umount /mnt/data
Notes

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
Notes

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

List USB devices

Display connected USB hardware.

bashLINUXusbhardwaredevices
bash
lsusb
Notes

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

List PCI devices

Display PCI and PCIe hardware.

bashLINUXpcihardwaredevices
bash
lspci -nn
Notes

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
Notes

Modern replacement for `ifconfig` on most Linux systems.

Show routing table

Display current IP routes.

bashLINUXiproutenetwork
bash
ip route show
Notes

Essential when debugging egress paths and default gateways.

List listening sockets

Show listening TCP and UDP ports with processes.

bashLINUXssportsnetwork
bash
ss -tulpn
Notes

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
Notes

Good first test for network reachability and latency.

Trace network path

Display the route packets take to a host.

bashLINUXtraceroutenetworkrouting
bash
traceroute example.com
Notes

Useful for diagnosing where connectivity breaks across hops.

Query DNS records

Look up DNS answers directly.

bashLINUXdnsdignetwork
bash
dig +short A example.com
Notes

Preferred over older tools for precise DNS debugging.

Basic DNS lookup

Query DNS information interactively or directly.

bashLINUXdnsnslookupnetwork
bash
nslookup example.com
Notes

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
Notes

Quick and minimal DNS utility.

Transfer data with URLs

Make HTTP requests and API calls.

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

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
Notes

Useful for unattended downloads and mirroring.

Open remote shell

Connect securely to another host.

bashLINUXsshremoteshell
bash
ssh user@server.example.com
Notes

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/
Notes

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/
Notes

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
Notes

Excellent for quick TCP connectivity tests.

Scan ports and services

Probe a host for open ports and services.

bashLINUXnmapportsnetwork
bash
nmap -sV example.com
Notes

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
Notes

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/
Notes

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/
Notes

Common format for source releases and backups.

Extract tarball

Unpack an archive into the current directory.

bashLINUXtarextractarchive
bash
tar -xzvf backup.tar.gz
Notes

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
Notes

Simple and widely supported compression format.

Decompress gzip file

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

bashLINUXgzipdecompress
bash
gunzip large.log.gz
Notes

Equivalent to `gzip -d`.

Create zip archive

Archive and compress files in zip format.

bashLINUXziparchivecompress
bash
zip -r release.zip dist/
Notes

Convenient when sharing with systems that expect zip.

Extract zip archive

Unpack zip files.

bashLINUXzipextract
bash
unzip release.zip -d release/
Notes

Simple cross-platform archive extraction.

Compress with xz

Compress a file using xz.

bashLINUXxzcompress
bash
xz -T0 dump.sql
Notes

Excellent compression ratios, often used for large text dumps.

Generate SHA-256 checksum

Compute file integrity digest.

bashLINUXchecksumsha256integrity
bash
sha256sum release.tar.gz
Notes

Useful for verifying downloads and release artifacts.

Generate MD5 checksum

Compute MD5 digest.

bashLINUXchecksummd5integrity
bash
md5sum file.iso
Notes

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
Notes

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
Notes

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
Notes

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
Notes

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
Notes

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
Notes

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

Pretty-print JSON

Format JSON output for readability.

bashLINUXjqjsonformat
bash
jq '.' response.json
Notes

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
Notes

Excellent for combining API JSON with shell pipelines.

Read YAML field

Extract data from YAML.

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

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)
Notes

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
Notes

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_
Notes

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
Notes

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

Start service

Start a service immediately.

bashLINUXsystemctlservicestart
bash
sudo systemctl start nginx
Notes

Use after install or when recovering a stopped service.

Stop service

Stop a running service.

bashLINUXsystemctlservicestop
bash
sudo systemctl stop nginx
Notes

Use before maintenance or configuration changes when needed.

Restart service

Restart a service cleanly.

bashLINUXsystemctlservicerestart
bash
sudo systemctl restart nginx
Notes

Common after config changes or deployments.

Reload service config

Ask a service to reload configuration without full restart.

bashLINUXsystemctlservicereload
bash
sudo systemctl reload nginx
Notes

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
Notes

Ensures the service starts automatically after reboot.

Disable service on boot

Remove boot-time activation for a unit.

bashLINUXsystemctlserviceboot
bash
sudo systemctl disable nginx
Notes

Useful for deprecated or temporary services.

List loaded units

Show active units known to systemd.

bashLINUXsystemctlunitsservice
bash
systemctl list-units --type=service
Notes

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
Notes

A standard service-specific log query on systemd systems.

Follow journal logs

Stream new journal entries live.

bashLINUXjournalctllogsfollow
bash
journalctl -fu nginx
Notes

Combines `-f` follow mode with unit filtering.

Show logs from current boot

Query logs for the active boot session.

bashLINUXjournalctlbootlogs
bash
journalctl -b
Notes

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
Notes

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
Notes

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
Notes

Classic disk inventory command.

Print partition layout

Inspect partitions with GNU Parted.

bashLINUXpartedpartitionsstorage
bash
sudo parted /dev/sda print
Notes

Useful for modern disks and scripted partition management.

Create ext4 filesystem

Format a block device with ext4.

bashLINUXmkfsext4filesystem
bash
sudo mkfs.ext4 /dev/sdb1
Notes

Formatting destroys existing data; verify the target device carefully.

Check filesystem

Check and repair a filesystem.

bashLINUXfsckrepairfilesystem
bash
sudo fsck -f /dev/sdb1
Notes

Run on unmounted filesystems when possible.

Mount device to path

Attach a filesystem to a mountpoint.

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

Ensure the mountpoint exists first.

Enable swap device or file

Activate swap space.

bashLINUXswapmemorystorage
bash
sudo swapon /swapfile
Notes

Useful when adding or restoring swap.

Disable swap device or file

Turn off swap usage.

bashLINUXswapmemorystorage
bash
sudo swapoff /swapfile
Notes

Ensure the system has enough RAM before disabling swap.

List physical volumes

Show LVM physical volumes.

bashLINUXlvmstoragepvs
bash
sudo pvs
Notes

Start here when inspecting LVM-backed systems.

List volume groups

Show LVM volume groups.

bashLINUXlvmstoragevgs
bash
sudo vgs
Notes

Useful for capacity and free-extent checks.

List logical volumes

Show LVM logical volumes.

bashLINUXlvmstoragelvs
bash
sudo lvs
Notes

Useful for seeing LV names, sizes, and attributes.

Extend logical volume

Increase logical volume size.

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

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
Notes

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
Notes

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
Notes

Useful for diagnosing disk saturation and queue depth.

Collect and report system activity

Use sysstat historical metrics.

bashLINUXsarperformancehistory
bash
sar -u 1 5
Notes

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
Notes

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
Notes

Helps connect system pressure to specific workloads.

List open files

Show files and sockets opened by processes.

bashLINUXlsoffilesports
bash
lsof -i :8080
Notes

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
Notes

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/
Notes

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'
Notes

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
Notes

Useful in scripts to avoid hanging forever.