Data & Development Cheat Sheet

Linux Commands Cheat Sheet: Essential Commands & Examples

A practical Linux command reference for navigating the terminal, managing files and permissions, finding text, monitoring processes, troubleshooting networks, installing packages, and administering everyday systems.

  • Copyable commands
  • Practical examples
  • Distribution notes
  • Safety warnings
20 structured sections Beginner to intermediate Ubuntu, Debian, Fedora, RHEL, and Arch guidance

Essential terminal commands

Linux Commands Quick Reference

Start with frequently used commands for navigation, files, text, processes, storage, networking, system information, and built-in documentation.

Essential Linux commands with examples
Task Command What it does Copy
Show current directory pwd Prints the absolute path of the current working directory.
List files ls -la Lists entries in long format, including hidden names.
Change directory cd /path/to/directory Changes the shell’s current working directory.
Create directories mkdir -p project/src Creates the directory and any missing parent directories.
Create an empty file touch notes.txt Creates the file if absent or updates its timestamps if it exists.
Copy a directory cp -r source/ backup/ Copies the source directory and its contents recursively.
Move or rename mv old-name.txt new-name.txt Moves an entry or renames it when both paths share a filesystem.
Remove with confirmation rm -i file.txt Prompts before removing the named file.
Read a text file less file.txt Opens text in a scrollable pager without editing the file.
Search text recursively grep -Rni "error" . Searches below the current directory and prints line numbers.
Find files by name find . -type f -name "*.log" Finds regular files ending in .log below the current directory.
Inspect processes ps aux Displays a snapshot of processes with user and resource details.
Check free disk space df -h Reports filesystem space using human-readable units.
Show network addresses ip address show Displays network interfaces and their configured addresses.
Show kernel and system details uname -a Prints available kernel, machine, and operating-system information.
Open command documentation man command Opens the installed manual page for a command when available.

Move around the filesystem

Terminal Navigation

Use these commands to identify your current location, inspect directories, and move efficiently between absolute and relative paths.

Linux terminal navigation commands with descriptions and examples
Command What it does Example Copy
pwd Prints the absolute path of the current working directory. pwd
ls Lists files and directories in the current location. ls
ls -lah Shows hidden entries, permissions, ownership, and human-readable sizes. ls -lah /var/log
cd /path/to/directory Moves to a directory using an absolute path. cd /var/log
cd directory Moves to a directory relative to the current location. cd projects
cd .. Moves up one level to the parent directory. cd ..
cd ../.. Moves up two directory levels. cd ../..
cd ~ Moves to the current user’s home directory. cd ~
cd - Returns to the previous working directory. cd -
realpath FILE Prints the resolved absolute path of a file or directory. realpath ./report.txt
pushd DIRECTORY Saves the current location on the directory stack and moves elsewhere. pushd /etc
popd Returns to the most recently saved directory on the stack. popd

Absolute path

An absolute path begins at the filesystem root and starts with /. It identifies the same location regardless of your current directory.

cd /home/alex/projects

Relative path

A relative path starts from your current directory. Use . for the current directory and .. for its parent.

cd ../shared

Manage filesystem objects

Files and Directories

Create, inspect, copy, move, rename, link, and safely remove files and directories from the Linux command line.

Linux commands for managing files and directories
Command What it does Example Copy
touch FILE Creates an empty file or updates an existing file’s timestamps. touch notes.txt
mkdir DIRECTORY Creates a new directory. mkdir reports
mkdir -p PATH Creates a directory and any missing parent directories. mkdir -p projects/site/assets
cp SOURCE DESTINATION Copies a file to another path. cp report.txt backup.txt
cp -r SOURCE DIRECTORY Recursively copies a directory and its contents. cp -r website website-backup
cp -a SOURCE DESTINATION Copies recursively while preserving metadata and symbolic links. cp -a config config-backup
mv SOURCE DESTINATION Moves a file or directory, or renames it at the same location. mv draft.txt final.txt
rm -i FILE Prompts for confirmation before removing a file. rm -i old-report.txt
rmdir DIRECTORY Removes a directory only when it is empty. rmdir empty-folder
ln -s TARGET LINK Creates a symbolic link that points to another path. ln -s /var/log/app.log app.log
stat FILE Displays detailed size, permission, ownership, and timestamp information. stat report.txt
file FILE Examines a file and reports its detected type. file archive.tar.gz
basename PATH Returns the final filename or directory component of a path. basename /var/log/syslog
dirname PATH Returns the directory portion of a path. dirname /var/log/syslog

Copy without accidental overwrites

Add -i to request confirmation when the destination already exists.

cp -i report.txt backups/report.txt

Rename several files carefully

Preview filenames before running a loop that modifies them. Quoting variables prevents spaces and wildcard characters from being split.

printf '%s\n' *.txt

Read and modify text

View and Edit Text Files

Display complete files, inspect selected lines, follow changing logs, summarize text, and open files in terminal-based editors.

Linux commands for viewing, editing, and processing text files
Command What it does Example Copy
cat FILE Writes the complete contents of one or more files to standard output. cat notes.txt
less FILE Opens a file in a scrollable viewer without loading it into an editor. less /var/log/syslog
head -n 20 FILE Displays the first 20 lines of a file. head -n 20 access.log
tail -n 20 FILE Displays the final 20 lines of a file. tail -n 20 access.log
tail -f FILE Continues displaying lines as they are appended to a file. tail -f app.log
nl FILE Displays text with line numbers added to non-empty lines. nl config.ini
wc -l FILE Counts newline characters, commonly used to report a file’s line count. wc -l users.csv
sort FILE Sorts text lines and writes the result to standard output. sort names.txt
sort FILE | uniq Sorts lines and collapses adjacent duplicate lines. sort names.txt | uniq
cut -d',' -f1 FILE Prints the first delimiter-separated field from every line. cut -d',' -f1 users.csv
tr 'a-z' 'A-Z' Translates lowercase ASCII letters to uppercase in standard input. tr 'a-z' 'A-Z' < names.txt
sed 's/OLD/NEW/g' FILE Replaces every occurrence of a pattern in the displayed output. sed 's/http:/https:/g' links.txt
nano FILE Opens a file in the Nano terminal text editor. nano notes.txt
vim FILE Opens a file in Vim when that editor is installed. vim notes.txt

Search inside less

Press /, type a search term, and press Enter. Use n for the next match, N for the previous match, and q to quit.

less application.log

Count unique values

Sort the input before using uniq -c, because uniq only detects duplicate lines that are adjacent.

sort status.txt | uniq -c | sort -nr

Locate files and matching content

Find Files and Search Text

Search the filesystem by name, type, size, or modification time, and find matching text inside individual files or complete directory trees.

Linux commands for locating files and searching text
Command What it does Example Copy
find PATH -name 'PATTERN' Searches below a path for names matching a case-sensitive pattern. find . -name '*.log'
find PATH -iname 'PATTERN' Searches for names without distinguishing uppercase and lowercase. find . -iname '*.jpg'
find PATH -type f Returns regular files while excluding directories and other file types. find ./reports -type f
find PATH -type d Returns directories below the selected path. find . -type d
find PATH -size +100M Finds entries larger than 100 mebibytes. find /var -type f -size +100M
find PATH -mtime -7 Finds entries modified within the last seven 24-hour periods. find . -type f -mtime -7
grep 'PATTERN' FILE Prints lines in a file that match a basic regular expression. grep 'ERROR' application.log
grep -in 'PATTERN' FILE Searches without case sensitivity and includes matching line numbers. grep -in 'warning' application.log
grep -Rni 'PATTERN' PATH Recursively searches readable files below a directory. grep -Rni 'database_url' ./config
grep -v 'PATTERN' FILE Prints lines that do not match the pattern. grep -v '^#' settings.conf
grep -E 'ONE|TWO' FILE Uses an extended regular expression to match either alternative. grep -E 'ERROR|WARNING' application.log
locate NAME Queries a filename database when the locate utility and database are available. locate nginx.conf
command -v COMMAND Reports the command that the current shell would execute. command -v python3
type COMMAND Identifies whether a name is an alias, function, builtin, or executable. type cd

Restrict the search depth

Use -maxdepth immediately after the starting path when you do not want find to descend through an entire tree.

find . -maxdepth 2 -type f -name '*.conf'

Use ripgrep when available

rg recursively searches text and normally respects ignore files such as .gitignore. It may need to be installed separately.

rg -n -i 'timeout' ./src

Control filesystem access

File Permissions and Ownership

Inspect and change read, write, and execute permissions for a file’s owner, group, and other users.

Linux commands for managing file permissions and ownership
Command What it does Example Copy
ls -l FILE Displays the file type, permission bits, owner, and group. ls -l deploy.sh
stat FILE Shows detailed metadata, including numeric and symbolic permissions. stat deploy.sh
chmod u+x FILE Adds execute permission for the file’s owner. chmod u+x deploy.sh
chmod g-w FILE Removes write permission from the file’s group. chmod g-w settings.conf
chmod 644 FILE Gives the owner read and write access and everyone else read-only access. chmod 644 settings.conf
chmod 755 FILE Gives the owner full access and everyone else read and execute access. chmod 755 deploy.sh
chmod -R MODE DIRECTORY Recursively changes permissions below a directory. chmod -R u+rwX project
chown USER FILE Changes the owner of a file when run with sufficient privileges. sudo chown alex report.txt
chown USER:GROUP FILE Changes both the owner and group of a file. sudo chown alex:developers app.conf
chgrp GROUP FILE Changes a file’s group ownership. chgrp developers report.txt
umask Displays the current mask used when permissions are assigned to new files. umask
umask 022 Sets a common session mask that removes group and other write permission. umask 022
getfacl FILE Displays access control list entries when ACL tools are installed. getfacl shared.txt
setfacl -m u:USER:rw FILE Grants a named user read and write access through an ACL entry. setfacl -m u:alex:rw shared.txt

Numeric permission values

Add 4 for read, 2 for write, and 1 for execute. The three digits represent the owner, group, and other users.

chmod 750 private-script.sh

Capital X for directories

In symbolic mode, X adds execute permission only to directories and files that already have an execute bit. This is useful for recursive directory changes.

chmod -R u+rwX,go+rX project

Manage local accounts

Users and Groups

Identify the current account, inspect group membership, and manage local users and groups with appropriate administrative privileges.

Linux commands for inspecting and managing users and groups
Command What it does Example Copy
whoami Prints the effective username of the current session. whoami
id Displays the current user ID, primary group, and supplementary groups. id
id USER Displays identity and group information for a specified account. id alex
groups USER Lists the groups associated with a user. groups alex
getent passwd USER Queries the configured account databases for a user entry. getent passwd alex
getent group GROUP Queries the configured account databases for a group entry. getent group developers
sudo useradd -m USER Creates a local account with a home directory on systems providing useradd. sudo useradd -m alex
sudo passwd USER Sets or changes the password for an account. sudo passwd alex
sudo usermod -aG GROUP USER Adds a user to a supplementary group without replacing existing memberships. sudo usermod -aG developers alex
sudo gpasswd -d USER GROUP Removes a user from a supplementary group. sudo gpasswd -d alex developers
sudo groupadd GROUP Creates a new local group. sudo groupadd developers
sudo usermod -l NEW OLD Changes an account’s login name but does not automatically rename its home directory. sudo usermod -l alexander alex
sudo userdel USER Removes a local account while normally leaving its home directory intact. sudo userdel olduser
last Displays recorded login sessions from the system login database. last

Debian and Ubuntu account creation

Debian-based systems commonly provide adduser, an interactive front end that creates the account, home directory, and initial configuration.

sudo adduser alex

Apply new group membership

Existing processes do not automatically receive newly assigned group memberships. The user normally needs to start a new login session.

id alex

Monitor and control programs

Processes and Jobs

Inspect running processes, locate process IDs, manage foreground and background jobs, adjust priority, and stop unresponsive programs.

Linux commands for monitoring and controlling processes and shell jobs
Command What it does Example Copy
ps aux Displays a detailed snapshot of processes from all users. ps aux
ps -ef Displays processes using a full-format, parent-oriented listing. ps -ef
top Opens an interactive, continuously updated process monitor. top
htop Opens a user-friendly interactive monitor when htop is installed. htop
pgrep PATTERN Returns process IDs whose names match a pattern. pgrep nginx
pgrep -af PATTERN Displays matching process IDs with their complete command lines. pgrep -af python
kill PID Sends SIGTERM, requesting that a process shut down cleanly. kill 4242
kill -KILL PID Immediately stops a process without allowing cleanup. kill -KILL 4242
pkill PATTERN Sends SIGTERM to processes whose names match a pattern. pkill firefox
jobs Lists jobs started from the current shell session. jobs
COMMAND & Starts a command as a background job in the current shell. python3 server.py &
bg %JOB Continues a stopped shell job in the background. bg %1
fg %JOB Brings a background or stopped job into the foreground. fg %1
nohup COMMAND & Runs a command while ignoring hangup signals and places it in the background. nohup ./backup.sh > backup.log 2>&1 &
nice -n VALUE COMMAND Starts a process with an adjusted CPU scheduling priority. nice -n 10 ./report.sh
renice VALUE -p PID Changes the nice value of an existing process when permitted. renice 10 -p 4242

Suspend a foreground job

Press Ctrl+Z to suspend the current foreground job. Then use bg to continue it in the background or fg to return it to the foreground.

jobs

Show a process tree

A process tree makes parent and child relationships easier to inspect. The standalone pstree utility may require a separate package on minimal installations.

ps -ef --forest

Inspect the operating environment

System Information

Identify the Linux distribution, kernel, hostname, architecture, hardware, memory, system time, and current uptime.

Linux commands for viewing system and hardware information
Command What it does Example Copy
uname -a Displays available kernel, hostname, release, and architecture information. uname -a
uname -r Prints the running kernel release. uname -r
uname -m Prints the machine hardware name, such as x86_64 or aarch64. uname -m
cat /etc/os-release Displays standardized operating-system identification data. cat /etc/os-release
hostname Prints the system’s current hostname. hostname
hostnamectl Displays hostname and system metadata on systems using systemd. hostnamectl
uptime Shows the current time, uptime, logged-in users, and load averages. uptime
date Displays the current system date, time, and timezone information. date
timedatectl Displays clock, timezone, and synchronization status on systemd systems. timedatectl
lscpu Displays CPU architecture, core, thread, and virtualization details. lscpu
free -h Displays memory and swap usage in human-readable units. free -h
lsblk Lists block devices and their mount relationships. lsblk
lspci Lists PCI devices when the pciutils package is installed. lspci
lsusb Lists USB devices when the usbutils package is installed. lsusb
who Displays users currently logged in and their terminal sessions. who

Show selected OS fields

The values in /etc/os-release are designed for scripts as well as human inspection. This example prints the distribution name and version.

grep -E '^(NAME|VERSION)=' /etc/os-release

Read Linux load averages

The three values shown by uptime represent average runnable or uninterruptible tasks over approximately 1, 5, and 15 minutes.

cat /proc/loadavg

Inspect storage and mounts

Disk and Filesystem Commands

Check free space, measure directory usage, inspect block devices and mount points, and safely work with Linux filesystems.

Linux commands for inspecting disks, storage, and filesystems
Command What it does Example Copy
df -h Displays used and available filesystem space in human-readable units. df -h
df -i Displays inode usage instead of storage blocks. df -i /var
du -sh PATH Reports the total apparent disk usage below a path. du -sh ~/Downloads
du -h --max-depth=1 PATH Summarizes usage for the immediate contents of a directory. du -h --max-depth=1 /var
lsblk -f Lists block devices with filesystem types, labels, UUIDs, and mount points. lsblk -f
findmnt Displays mounted filesystems in a tree-like structure. findmnt
findmnt PATH Identifies the mounted filesystem containing a selected path. findmnt /home
blkid Displays available block-device attributes such as UUID and filesystem type. sudo blkid
sudo fdisk -l Lists recognized disks and partition tables without changing them. sudo fdisk -l
sudo mount DEVICE PATH Mounts a filesystem at an existing directory. sudo mount /dev/sdb1 /mnt/backup
sudo umount PATH Detaches a mounted filesystem after active use has stopped. sudo umount /mnt/backup
sync Requests that buffered filesystem writes be committed to persistent storage. sync
sudo fsck DEVICE Checks and may repair an unmounted filesystem using the appropriate checker. sudo fsck /dev/sdb1
ncdu PATH Opens an interactive disk-usage browser when ncdu is installed. ncdu /var

Find large top-level entries

Summarize the immediate contents of a directory and sort the human-readable results from largest to smallest.

du -h --max-depth=1 . | sort -hr

Check what keeps a mount busy

If unmounting reports that a target is busy, inspect processes using the mount before closing them normally. The fuser utility may be supplied by an additional package.

sudo fuser -vm /mnt/backup

Package and compress files

Archives and Compression

Create, inspect, extract, and compress archives using common Linux formats such as tar, gzip, xz, and ZIP.

Linux commands for creating, inspecting, and extracting compressed archives
Command What it does Example Copy
tar -cf ARCHIVE.tar PATH Creates an uncompressed tar archive from files or directories. tar -cf project.tar project/
tar -czf ARCHIVE.tar.gz PATH Creates a tar archive compressed with gzip. tar -czf project.tar.gz project/
tar -cJf ARCHIVE.tar.xz PATH Creates a tar archive compressed with xz. tar -cJf project.tar.xz project/
tar -tf ARCHIVE.tar Lists archive members without extracting them. tar -tf project.tar.gz
tar -xf ARCHIVE.tar Extracts an archive into the current directory. tar -xf project.tar.gz
tar -xf ARCHIVE.tar -C DIRECTORY Extracts an archive into an existing destination directory. tar -xf project.tar.gz -C /tmp/project
gzip FILE Compresses a file to FILE.gz and normally removes the original file. gzip access.log
gzip -k FILE Creates a gzip-compressed copy while keeping the original file. gzip -k access.log
gunzip FILE.gz Decompresses a gzip file and normally removes the compressed version. gunzip access.log.gz
xz -k FILE Creates an xz-compressed copy while preserving the original file. xz -k database.sql
unxz FILE.xz Decompresses an xz file and normally removes the compressed version. unxz database.sql.xz
zip -r ARCHIVE.zip PATH Recursively creates a ZIP archive when the zip utility is installed. zip -r project.zip project/
unzip -l ARCHIVE.zip Lists ZIP archive members without extracting them. unzip -l project.zip
unzip ARCHIVE.zip -d DIRECTORY Extracts a ZIP archive into a selected directory. unzip project.zip -d /tmp/project

Extract one archive member

Supply the member’s path exactly as it appears in the archive listing to extract only that file.

tar -xf project.tar.gz project/README.md

Stream compressed text

Use zcat to send gzip-compressed text to standard output without creating an uncompressed file on disk.

zcat access.log.gz | less

Diagnose network connectivity

Networking Commands

Inspect interfaces and routes, test connectivity, query DNS, examine listening sockets, and transfer data over common network protocols.

Linux commands for inspecting and troubleshooting network connections
Command What it does Example Copy
ip address show Displays network interfaces and their assigned addresses. ip address show
ip link show Displays network interfaces and their link states. ip link show
ip route show Displays the current IPv4 routing table. ip route show
ping -c 4 HOST Sends four ICMP echo requests to test reachability and latency. ping -c 4 example.com
ss -tuln Lists listening TCP and UDP sockets using numeric addresses and ports. ss -tuln
sudo ss -tulpn Lists listening sockets and available process information. sudo ss -tulpn
curl -I URL Requests HTTP response headers without downloading the response body. curl -I https://example.com
curl -O URL Downloads a resource using the filename from its URL path. curl -O https://example.com/file.zip
wget URL Downloads a resource when the wget utility is installed. wget https://example.com/file.zip
dig DOMAIN Queries DNS and displays detailed response information. dig example.com
dig +short DOMAIN Prints a concise DNS answer, commonly an address or hostname. dig +short example.com
host DOMAIN Performs a concise DNS lookup when the host utility is installed. host example.com
traceroute HOST Displays network hops toward a destination when traceroute is installed. traceroute example.com
resolvectl status Displays DNS configuration on systems using systemd-resolved. resolvectl status
nmcli device status Displays interface status on systems managed by NetworkManager. nmcli device status

Test a TCP port

Use Bash’s TCP redirection when supported to test whether a remote TCP connection can be opened. A successful command normally produces no output.

timeout 5 bash -c '</dev/tcp/example.com/443'

Discover the public IP address

This sends a request to an external service. Use only a service you trust, because it receives the requesting public IP address.

curl https://api.ipify.org

Install and update software

Package Management

Search, install, update, inspect, and remove software using the package manager provided by your Linux distribution.

Package management commands for major Linux distributions
Command What it does Distribution Copy
sudo apt update Refreshes available package information from configured repositories. Debian, Ubuntu
sudo apt upgrade Upgrades installed packages when dependencies can be satisfied without removing packages. Debian, Ubuntu
sudo apt install PACKAGE Installs a package and required dependencies. Debian, Ubuntu
sudo apt remove PACKAGE Removes a package while normally retaining its system configuration files. Debian, Ubuntu
apt search TERM Searches available package names and descriptions. Debian, Ubuntu
dpkg -L PACKAGE Lists files installed by a local Debian package. Debian, Ubuntu
sudo dnf upgrade Refreshes metadata as needed and upgrades installed packages. Fedora, RHEL family
sudo dnf install PACKAGE Installs a package and resolves its dependencies. Fedora, RHEL family
sudo dnf remove PACKAGE Removes a package and dependencies that are no longer required. Fedora, RHEL family
dnf search TERM Searches enabled package repositories. Fedora, RHEL family
rpm -ql PACKAGE Lists files installed by an RPM package. RPM-based systems
sudo pacman -Syu Refreshes package databases and performs a full system upgrade. Arch Linux
sudo pacman -S PACKAGE Installs or upgrades a package from synchronized repositories. Arch Linux
sudo pacman -Rns PACKAGE Removes a package, unused dependencies, and associated backup configuration files. Arch Linux
pacman -Ss TERM Searches synchronized package databases. Arch Linux
sudo zypper refresh Refreshes repository metadata. openSUSE, SUSE
sudo zypper install PACKAGE Installs a package using configured repositories. openSUSE, SUSE

Identify the package manager

Read the operating-system identification file before choosing distribution-specific instructions.

cat /etc/os-release

Find which package owns a file

Use the database command appropriate for the installed package format.

dpkg -S /usr/bin/curl

Control system services

Services and systemd

Inspect, start, stop, restart, enable, and troubleshoot service units on Linux systems that use systemd.

Linux systemctl commands for managing systemd services
Command What it does Example Copy
systemctl status UNIT Shows the unit’s current state and recent log messages. systemctl status ssh.service
sudo systemctl start UNIT Starts a unit for the current boot without enabling future startup. sudo systemctl start nginx.service
sudo systemctl stop UNIT Stops a running unit. sudo systemctl stop nginx.service
sudo systemctl restart UNIT Stops and starts a unit, interrupting the running service. sudo systemctl restart nginx.service
sudo systemctl reload UNIT Requests a supported service to reload configuration without a full restart. sudo systemctl reload nginx.service
sudo systemctl enable UNIT Configures a unit to start through its defined boot dependencies. sudo systemctl enable nginx.service
sudo systemctl enable --now UNIT Enables a unit for future boots and starts it immediately. sudo systemctl enable --now nginx.service
sudo systemctl disable UNIT Removes enablement links but does not necessarily stop a running unit. sudo systemctl disable nginx.service
systemctl is-active UNIT Reports whether a unit is currently active. systemctl is-active nginx.service
systemctl is-enabled UNIT Reports the unit’s enablement state. systemctl is-enabled nginx.service
systemctl --failed Lists units currently in a failed state. systemctl --failed
systemctl list-units --type=service Lists service units currently loaded by systemd. systemctl list-units --type=service
systemctl list-unit-files --type=service Lists installed service unit files and their enablement states. systemctl list-unit-files --type=service
sudo systemctl daemon-reload Makes systemd reread unit files after they have been changed. sudo systemctl daemon-reload
systemctl cat UNIT Displays the unit’s backing files and drop-in configuration. systemctl cat nginx.service

Create a unit override

Use systemctl edit to create a drop-in override instead of modifying a vendor-supplied unit file directly.

sudo systemctl edit nginx.service

Manage a user service

Add --user to manage units belonging to the current user’s systemd manager rather than the system manager.

systemctl --user status my-app.service

Inspect recorded system events

Logs and journalctl

Filter systemd journal entries by boot, service, time, priority, or kernel source, and inspect traditional text logs where available.

Linux commands for viewing systemd journal and text log entries
Command What it does Example Copy
journalctl Displays entries available in the systemd journal. journalctl
journalctl -b Displays journal entries from the current boot. journalctl -b
journalctl -b -1 Displays entries from the previous boot when retained journal data is available. journalctl -b -1
journalctl -u UNIT Filters entries associated with a systemd unit. journalctl -u nginx.service
journalctl -u UNIT -f Follows new journal entries for a selected unit. journalctl -u nginx.service -f
journalctl -n NUMBER Displays the requested number of most recent entries. journalctl -n 100
journalctl -p err Shows entries at error priority and more severe levels. journalctl -p err -b
journalctl --since TIME Displays entries on or after a specified date or relative time. journalctl --since "1 hour ago"
journalctl --since START --until END Restricts entries to a selected time range. journalctl --since "09:00" --until "10:00"
journalctl -k Displays kernel messages from the current boot by default. journalctl -k
journalctl --disk-usage Reports disk space currently used by journal files. journalctl --disk-usage
sudo journalctl --vacuum-time=14d Removes archived journal files older than the selected retention period. sudo journalctl --vacuum-time=14d
tail -f LOGFILE Follows appended lines in a traditional text log. sudo tail -f /var/log/syslog
grep -i 'PATTERN' LOGFILE Finds matching lines in a readable text log without case sensitivity. sudo grep -i 'failed' /var/log/auth.log

Show concise service errors

Combine unit, boot, and priority filters to reduce unrelated output while troubleshooting a failed service.

journalctl -u nginx.service -b -p err --no-pager

Use precise timestamps

Include a full date when investigating older incidents so relative expressions and day boundaries do not select the wrong period.

journalctl --since "2026-08-16 09:00:00" --until "2026-08-16 10:00:00"

Connect and transfer securely

SSH and Remote Transfers

Open encrypted remote sessions, authenticate with SSH keys, transfer files, synchronize directories, and create secure port forwards.

Linux SSH commands for remote access and secure file transfers
Command What it does Example Copy
ssh USER@HOST Opens an encrypted shell session on a remote SSH server. ssh alex@server.example.com
ssh -p PORT USER@HOST Connects to an SSH server listening on a nondefault port. ssh -p 2222 alex@server.example.com
ssh -i KEY USER@HOST Uses a selected private identity file for authentication. ssh -i ~/.ssh/work_ed25519 alex@server.example.com
ssh USER@HOST COMMAND Runs one command remotely and returns its output. ssh alex@server.example.com 'uptime'
ssh-keygen -t ed25519 -C 'LABEL' Creates an Ed25519 key pair and prompts for its location and passphrase. ssh-keygen -t ed25519 -C 'alex@example.com'
ssh-copy-id USER@HOST Installs a public key for remote authentication when the utility is available. ssh-copy-id alex@server.example.com
scp FILE USER@HOST:PATH Copies a local file to a remote path using SSH transport. scp report.pdf alex@server.example.com:/home/alex/
scp USER@HOST:FILE PATH Copies a remote file to a local destination. scp alex@server.example.com:/var/tmp/report.pdf ./
scp -r DIRECTORY USER@HOST:PATH Recursively copies a local directory to a remote path. scp -r website alex@server.example.com:/srv/backups/
sftp USER@HOST Starts an interactive SSH File Transfer Protocol session. sftp alex@server.example.com
rsync -av SOURCE USER@HOST:PATH Synchronizes files while preserving common metadata and showing progress details. rsync -av website/ alex@server.example.com:/srv/website/
rsync -av --dry-run SOURCE DESTINATION Previews which files rsync would transfer or update. rsync -av --dry-run website/ alex@server.example.com:/srv/website/
ssh -L LOCAL:HOST:REMOTE USER@SERVER Forwards a local TCP port through the SSH server to another host and port. ssh -L 8080:127.0.0.1:80 alex@server.example.com
ssh-keygen -F HOST Searches known-host entries for a hostname or address. ssh-keygen -F server.example.com

Create a reusable SSH host alias

Add host settings to ~/.ssh/config so connections can reuse the same hostname, username, port, and identity file.

ssh production

Verify a private key’s permissions

OpenSSH rejects private keys that are accessible too broadly. Limit access to the owning user.

chmod 600 ~/.ssh/work_ed25519

Work faster in the shell

Bash Shortcuts and Command History

Edit commands efficiently, search previous commands, control terminal jobs, and reuse selected arguments from Bash history.

Bash keyboard shortcuts and command history expressions
Shortcut or command What it does Typical use Copy
Ctrl+C Sends an interrupt signal to the current foreground process. Stop a running command.
Ctrl+Z Suspends the current foreground job. Pause a command before using bg or fg.
Ctrl+A Moves the cursor to the beginning of the command line. Edit the command or add a prefix.
Ctrl+E Moves the cursor to the end of the command line. Continue typing after editing earlier text.
Ctrl+U Cuts text from the cursor back to the beginning of the line. Remove an incorrect command prefix.
Ctrl+K Cuts text from the cursor to the end of the line. Remove remaining command arguments.
Ctrl+W Cuts the word before the cursor. Remove the previous argument or path component.
Ctrl+Y Pastes text most recently cut with a Readline shortcut. Restore text removed with Ctrl+U or Ctrl+K.
Ctrl+R Starts a reverse incremental search through command history. Find a previously used command by typing part of it.
Ctrl+L Clears the terminal display while preserving shell history. Get a clean screen without deleting commands.
Tab Completes commands, paths, or supported arguments. Reduce typing and avoid path spelling errors.
history Displays commands retained in the current Bash history list. history
history | grep TERM Filters displayed history for matching text. history | grep ssh
!! Expands to the complete previous command. sudo !! reruns the previous command with sudo.
!$ Expands to the final argument of the previous command. less !$ reuses the previous final argument.
!NUMBER Expands to the command with the selected history number. !125
Alt+. Inserts the final argument from a previous command. Press repeatedly to move through earlier final arguments.

Reuse a command without executing it

Add :p to a history expansion to print the expanded command and place it in history instead of running it immediately.

!!:p

Save current session history

Bash normally writes history when the shell exits. This command appends new entries from the current session to the history file.

history -a

Connect commands and control output

Pipes, Redirection, and Command Chaining

Send output between commands, read input from files, separate standard output from errors, and run commands conditionally.

Bash operators for pipes, redirection, and command chaining
Operator What it does Example Copy
COMMAND1 | COMMAND2 Sends standard output from the first command to standard input of the second. ps aux | grep nginx
COMMAND > FILE Writes standard output to a file, replacing its existing contents. date > timestamp.txt
COMMAND >> FILE Appends standard output to the end of a file. date >> timestamps.txt
COMMAND < FILE Provides a file as standard input to a command. sort < names.txt
COMMAND 2> FILE Writes standard error to a file, replacing its existing contents. find / -name '*.conf' 2> errors.log
COMMAND 2>> FILE Appends standard error to the end of a file. ./backup.sh 2>> backup-errors.log
COMMAND > FILE 2>&1 Writes standard output and standard error to the same file. ./backup.sh > backup.log 2>&1
COMMAND | tee FILE Displays standard output and also writes it to a file. df -h | tee disk-report.txt
COMMAND | tee -a FILE Displays standard output and appends it to a file. date | tee -a activity.log
COMMAND1 && COMMAND2 Runs the second command only when the first returns a successful status. mkdir reports && cd reports
COMMAND1 || COMMAND2 Runs the second command only when the first returns a nonzero status. ping -c 1 example.com || echo 'Host unavailable'
COMMAND1 ; COMMAND2 Runs commands sequentially regardless of the first command’s status. date ; uptime
COMMAND | xargs COMMAND Builds command arguments from standard input. printf '%s\n' file1 file2 | xargs wc -l
COMMAND & Starts a command as a background job in the current shell. ./report.sh &

Preserve pipeline failures

By default, a pipeline’s status usually comes from its final command. Enable pipefail when a script should also detect failure from an earlier pipeline stage.

set -o pipefail

Handle filenames safely with xargs

Use null-delimited output and input when filenames may contain spaces, quotes, or newline characters.

find . -type f -print0 | xargs -0 wc -l

Customize the shell environment

Environment Variables and Shell Configuration

Inspect and set environment variables, update the executable search path, reload Bash configuration, and create reusable aliases.

Linux commands for environment variables and Bash configuration
Command What it does Example Copy
env Displays environment variables passed to the current process. env
printenv VARIABLE Prints the exported value of a selected environment variable. printenv HOME
echo "$VARIABLE" Expands and displays a shell variable while preserving its spacing. echo "$PATH"
VARIABLE='VALUE' Creates or updates a variable in the current shell. PROJECT_DIR="$HOME/projects/site"
export VARIABLE='VALUE' Sets a variable and exports it to subsequently started child processes. export EDITOR='nano'
unset VARIABLE Removes a variable or function from the current shell. unset PROJECT_DIR
VARIABLE='VALUE' COMMAND Supplies a variable to one command without permanently changing the shell. LANG=C sort names.txt
export PATH="$HOME/bin:$PATH" Adds a personal executable directory before the existing command search path. export PATH="$HOME/bin:$PATH"
source FILE Reads and executes a file in the current shell environment. source ~/.bashrc
. FILE Uses the portable dot syntax to read a file in the current shell. . ~/.profile
alias NAME='COMMAND' Creates a command alias for the current shell session. alias ll='ls -lah'
unalias NAME Removes an alias from the current shell session. unalias ll
type NAME Shows how the shell resolves an alias, function, builtin, or executable. type ll
bash --noprofile --norc Starts Bash without reading normal personal startup files. bash --noprofile --norc

Common Bash startup files

Interactive non-login Bash shells commonly read ~/.bashrc. Login shells read the first available file among ~/.bash_profile, ~/.bash_login, and ~/.profile.

nano ~/.bashrc

Test a clean environment

Use env -i to start a command with an initially empty environment, then provide only the variables it requires.

env -i HOME="$HOME" PATH="/usr/bin:/bin" bash --noprofile --norc

Diagnose problems safely

Troubleshooting, Safety, and FAQ

Use a structured troubleshooting process, inspect command failures, and reduce risk before changing files, services, permissions, or storage.

Linux troubleshooting commands and diagnostic checks
Command What it checks Example Copy
echo $? Displays the exit status of the most recently completed foreground pipeline. echo $?
command -v COMMAND Checks whether the current shell can resolve a command name. command -v curl
type -a COMMAND Shows every shell alias, function, builtin, or executable matching a name. type -a python3
systemctl --failed Lists systemd units currently in a failed state. systemctl --failed
journalctl -p err -b Shows error-level and more severe journal entries from the current boot. journalctl -p err -b
dmesg --level=err,warn Displays available kernel ring-buffer errors and warnings on supporting systems. sudo dmesg --level=err,warn
df -h Checks whether a mounted filesystem is running out of storage space. df -h
df -i Checks whether a filesystem has exhausted its available inodes. df -i
free -h Displays current memory and swap usage. free -h
ip route show Checks current routes, including the default gateway when configured. ip route show
sudo -l Lists the current user’s permitted and prohibited sudo commands. sudo -l
man COMMAND Opens the installed manual page for a command. man rsync
COMMAND --help Requests concise usage information from commands that support this option. find --help
help BUILTIN Displays Bash documentation for a shell builtin. help cd

Why does Linux say “command not found”?

The program may not be installed, its directory may be missing from PATH, or the command name may be incorrect. Check it with command -v, then use the correct distribution package manager if installation is required.

What does “permission denied” mean?

The current user may lack permission to read, write, execute, or traverse the target. Inspect the complete path with namei -l PATH when available, and correct ownership or permissions instead of automatically using sudo.

Why can a disk appear full when files are small?

The filesystem may have exhausted its inodes, deleted files may still be held open by processes, or data may exist beneath a mount point. Compare df -h, df -i, and du before deleting anything.

Should every administrative command use sudo?

No. Use normal user privileges whenever possible and elevate only the specific command that requires administrative access. Review the command, resolved paths, wildcards, and expected result first.

Are Linux commands identical on every distribution?

Core command behavior is often similar, but package managers, filesystem layouts, service names, defaults, installed utilities, and tool versions can differ. Check the local manual and your distribution’s official documentation.

How should a failing command be investigated?

Preserve the exact error, check the exit status, confirm inputs and permissions, reproduce the problem with the smallest safe command, and inspect relevant logs before changing the system.