Home / Software / Linux / Linux Commands Cheat Sheet: Home Lab and Server Reference

Linux Commands Cheat Sheet: Home Lab and Server Reference

Linux Commands Cheat Sheet: Home Lab and Server Reference

This reference covers Ubuntu and Debian-based distributions and is aimed at server administrators and home lab builders running systems such as Ubuntu Server, Proxmox, Docker hosts, and NAS platforms. Commands are intended for use in a standard bash terminal. Where a command requires elevated privileges, sudo is noted or implied.

CommandWhat it doesExample / Notes
pwdPrint working directoryShows your current full path
lsList directory contentsls /etc
ls -laList all files including hidden, with permissions and ownershipUse this to inspect dotfiles and symlinks
ls -lhList with human-readable file sizesShows KB, MB, GB instead of byte counts
cdChange directorycd /var/log
cd ~Change to home directoryEquivalent to cd /home/username
cd -Return to previous directoryToggles between two locations
mkdir dirnameCreate a directorymkdir backups
mkdir -pCreate nested directories, no error if they existmkdir -p /opt/myapp/config
rm fileRemove a fileNo recycle bin — deletion is permanent
rm -rf /pathRecursively force-delete a directory and all contentsUse with extreme caution. No confirmation prompt.
cp source destCopy a filecp config.yml config.yml.bak
cp -r src/ dest/Recursively copy a directorycp -r /etc/nginx /etc/nginx.bak
mv source destMove or rename a file or directorymv old.conf new.conf
touch filenameCreate an empty file or update timestampstouch deploy.log
find /path -name "*.conf"Find files by name patternfind /etc -name "*.conf" -type f
locate filenameFast filename search using a pre-built indexRun sudo updatedb first to refresh the index
which commandShow the path of an executablewhich python3
whereis commandShow binary, source, and man page locationswhereis nginx
treeDisplay directory structure as a treeInstall with apt install tree; use tree -L 2 to limit depth

Viewing and Editing Files

CommandWhat it doesExample / Notes
cat filePrint entire file contents to terminalcat /etc/hosts
less filePage through a file interactivelyArrow keys to scroll, q to quit, /term to search
more filePage through a file (forward only)Older alternative to less
head -n 20 fileShow the first 20 lines of a filehead -n 50 /var/log/syslog
tail -n 20 fileShow the last 20 lines of a filetail -n 100 /var/log/nginx/error.log
tail -f fileFollow a log file in real timetail -f /var/log/syslog — Ctrl+C to stop
grep "pattern" fileSearch for a pattern in a filegrep "error" /var/log/nginx/error.log
grep -r "pattern" /pathRecursive search across all files in a directorygrep -r "listen 80" /etc/nginx/
grep -i "pattern" fileCase-insensitive searchgrep -i "failed" /var/log/auth.log
grep -v "pattern" fileShow lines that do not matchgrep -v "^#" /etc/ssh/sshd_config — strip comments
wc -l fileCount the number of lines in a filewc -l /etc/passwd
diff file1 file2Show differences between two filesdiff nginx.conf nginx.conf.bak
nano fileOpen a file in the nano text editorCtrl+O to save, Ctrl+X to exit
vim fileOpen a file in the vim text editori to insert; Esc then :wq to save and quit; :q! to quit without saving

Permissions and Ownership

Understanding ls -la output

-rwxr-xr-x  1  ubuntu  www-data  4096  May 10 09:00  script.sh
 |||||||||      |       |
 ||||||||+-- other: r-x (read, execute)
 |||||+++--- group: r-x (read, execute)
 ||+++------ owner: rwx (read, write, execute)
 |+--------- file type: - file, d directory, l symlink

Numeric permission reference

ModeMeaningCommon use
755Owner: rwx | Group: r-x | Other: r-xDirectories, public scripts
644Owner: rw- | Group: r– | Other: r–Config files, web assets
600Owner: rw- | Group: — | Other: —SSH private keys, secrets
700Owner: rwx | Group: — | Other: —Private scripts, ~/.ssh directory
777Everyone: rwxAvoid on servers — full access for all users

Permission and ownership commands

CommandWhat it doesExample / Notes
chmod 755 fileSet permissions numericallychmod 644 /etc/nginx/nginx.conf
chmod +x fileMake a file executablechmod +x deploy.sh
chmod -R 755 /pathRecursively set permissions on a directorychmod -R 755 /var/www/html
chown user:group fileChange owner and group of a filechown ubuntu:ubuntu app.conf
chown -R www-data:www-data /var/wwwRecursively assign web server ownershipStandard for Nginx/Apache web roots
chgrp groupname fileChange only the group of a filechgrp docker /var/run/docker.sock
sudo commandRun a command as rootsudo systemctl restart nginx
su -Switch to the root user (full login shell)Requires root password; not available on Ubuntu by default
whoamiPrint the current userUseful inside scripts to confirm execution context
idShow UID, GID, and group membershipsid ubuntu
groupsList groups the current user belongs togroups username

User and Group Management

CommandWhat it doesExample / Notes
useradd usernameCreate a new user (low-level, minimal)Does not create home directory by default; use -m flag to create one
adduser usernameCreate a new user interactively (Debian/Ubuntu)Preferred on Ubuntu — prompts for password and details, creates home directory
usermod -aG group usernameAdd a user to a supplementary groupusermod -aG sudo username — grant sudo access; usermod -aG docker username
usermod -l newname oldnameRename a user accountDoes not rename home directory — do that separately
userdel usernameDelete a user accountAdd -r to also remove the home directory
passwd usernameSet or change a user’s passwordsudo passwd ubuntu
groupadd groupnameCreate a new groupgroupadd developers
groupdel groupnameDelete a groupUsers are not deleted when a group is removed
cat /etc/passwdList all user accountsFormat: username:x:UID:GID:info:home:shell
cat /etc/groupList all groups and their membersFormat: groupname:x:GID:members

Process Management

CommandWhat it doesExample / Notes
ps auxList all running processes with resource usageColumns: USER, PID, %CPU, %MEM, COMMAND
ps aux | grep nginxFilter process list by namePipe with grep -v grep to exclude the grep process itself
topReal-time process monitorq to quit; k to kill a process by PID
htopInteractive process viewer with colour outputInstall with apt install htop; F9 to kill, F6 to sort
kill PIDSend SIGTERM (graceful stop) to a processkill 3421
kill -9 PIDSend SIGKILL (force-terminate) to a processUse when a graceful kill does not work
killall processnameKill all processes matching a namekillall nginx
pkill processnameSend a signal to processes matching a name patternpkill -HUP nginx — send reload signal
pgrep processnameReturn PIDs of matching processespgrep nginx
nohup command &Run a command that persists after logoutnohup ./backup.sh & — output goes to nohup.out
jobsList background and suspended jobs in the current shellShows job numbers used with fg and bg
fg %1Bring a background job to the foregroundUse job number from jobs
bg %1Resume a suspended job in the backgroundUse after Ctrl+Z to suspend
command &Run a command immediately in the background./long-script.sh &
Ctrl+CInterrupt (terminate) the current foreground processSends SIGINT
Ctrl+ZSuspend the current foreground processResume with fg or bg

Disk and Storage

CommandWhat it doesExample / Notes
df -hShow disk space usage for all mounted filesystemsHuman-readable sizes; check Use% column
du -sh /pathShow total size of a directorydu -sh /var/log
du -sh *Show size of each item in the current directoryRun from / or /var to identify large directories
lsblkList block devices and their mount pointsShows disks, partitions, and LVM volumes in a tree layout
fdisk -lList partition tables for all disksRequires root; use sudo fdisk -l
mount /dev/sdb1 /mnt/dataMount a partition to a directoryDirectory must exist first; use mkdir -p /mnt/data
umount /mnt/dataUnmount a filesystemEnsure no processes are using the mount point first
blkidShow UUIDs and filesystem types of block devicesUse UUIDs in /etc/fstab for reliable mounting
free -hShow RAM and swap usageMonitor available column for actual free memory
vmstatShow virtual memory, CPU, and I/O statisticsvmstat 2 5 — sample every 2 seconds, 5 times
iostatShow CPU and disk I/O statisticsInstall with apt install sysstat; use iostat -x 1 for extended stats
ncduInteractive disk usage browserInstall with apt install ncdu; navigate with arrow keys, d to delete

Network Commands

CommandWhat it doesExample / Notes
ip aShow all network interfaces and IP addressesModern replacement for ifconfig
ip addr show eth0Show details for a specific interfaceReplace eth0 with your interface name (e.g., ens3, enp3s0)
ip routeShow the routing tableCheck default gateway with ip route | grep default
ifconfigLegacy network interface configuration toolInstall with apt install net-tools; use ip a instead where possible
ping hostTest connectivity to a hostping -c 4 8.8.8.8 — send 4 packets then stop
curl URLTransfer data from a URLcurl -I https://example.com — fetch headers only; curl -o file URL to download
wget URLDownload a file from a URLwget -O filename.tar.gz URL
netstat -tulpnShow listening ports and associated processesRequires net-tools; use ss -tulpn instead on modern systems
ss -tulpnShow listening TCP/UDP ports and the processes using themFaster and more accurate than netstat
nmap hostScan open ports on a hostnmap -sV 192.168.1.1 — detect service versions; install with apt install nmap
traceroute hostTrace the network path to a hosttraceroute 8.8.8.8; install with apt install traceroute
dig domainPerform a DNS lookup with detailed outputdig serverman.co.uk A; dig @8.8.8.8 domain to query a specific resolver
nslookup domainSimple DNS query toolnslookup serverman.co.uk
host domainBrief DNS lookup outputhost serverman.co.uk
arp -aShow ARP cache (IP to MAC address mappings)Useful for finding devices on the local network
ip neighShow neighbour (ARP) tableModern equivalent of arp -a
hostnamePrint the system hostnameChange permanently with hostnamectl set-hostname newname
hostname -IPrint all local IP addressesQuick way to find your server’s IP
ufw statusShow UFW firewall status and rulessudo ufw status verbose for full output
ufw allow 22Allow inbound traffic on a portsudo ufw allow 22/tcp; also ufw allow 'Nginx Full'
ufw enableEnable the UFW firewallEnsure SSH is allowed before enabling: sudo ufw allow ssh

System Information

CommandWhat it doesExample / Notes
uname -aShow all system information (kernel, hostname, architecture)Full system summary in one line
uname -rShow the running kernel versionUseful before and after kernel upgrades
hostnamectlShow detailed system identity and OS informationIncludes hostname, machine ID, OS, kernel, and architecture
lscpuShow CPU architecture detailsCores, threads, cache, virtualisation support
lsmemShow memory range and size informationUse free -h for a simpler usage summary
lspciList PCI deviceslspci | grep -i vga — identify GPU
lsusbList USB devicesUseful for identifying connected hardware in a home lab
dmidecodeRead hardware information from DMI/SMBIOS tablessudo dmidecode -t memory — show RAM module details
cat /etc/os-releaseShow OS name and versionReliable way to identify the distribution and version
uptimeShow how long the system has been running and load averagesLoad average values: 1min, 5min, 15min
whoShow currently logged-in usersIncludes terminal and login time
lastShow history of user logins and system rebootslast reboot — list reboot history only
historyShow command history for the current userhistory | grep apt — search history; !123 to re-run command 123
dmesgPrint the kernel ring buffer (boot and hardware messages)Use sudo dmesg for full output
dmesg | tail -20Show the last 20 kernel messagesUseful for diagnosing hardware errors and USB events

Package Management (apt — Ubuntu/Debian)

CommandWhat it doesExample / Notes
apt updateRefresh the package index from repositoriesAlways run before installing or upgrading packages
apt upgradeUpgrade installed packages without removing anySafe for routine updates; will not install new dependencies that require package removal
apt full-upgradeUpgrade packages, adding or removing dependencies as neededUse for distribution upgrades or when apt upgrade holds packages back
apt install packageInstall a packageapt install nginx curl git — multiple packages in one command
apt remove packageRemove a package, keeping configuration filesapt remove nginx
apt purge packageRemove a package and its configuration filesUse this for a clean removal
apt autoremoveRemove orphaned packages no longer needed as dependenciesRun periodically after upgrades to free disk space
apt search termSearch for packages by keywordapt search "web server"
apt show packageDisplay detailed information about a packageShows version, dependencies, description
apt list --installedList all installed packagesPipe to grep package to check if something is installed
dpkg -lList all installed packages (low-level)Status codes: ii = installed, rc = removed but config remains
dpkg -l | grep packageCheck if a specific package is installeddpkg -l | grep nginx
add-apt-repository ppa:nameAdd a PPA (Personal Package Archive)add-apt-repository ppa:ondrej/php; run apt update afterwards
apt-cache policy packageShow installed version, candidate version, and repository priorityUseful for pinning or debugging version conflicts

systemd Service Management

CommandWhat it doesExample / Notes
systemctl status serviceShow the current status and recent logs for a servicesystemctl status nginx
systemctl start serviceStart a service immediatelysudo systemctl start docker
systemctl stop serviceStop a service immediatelysudo systemctl stop apache2
systemctl restart serviceStop and start a serviceCauses a brief interruption; use reload where supported
systemctl reload serviceReload configuration without stopping the servicesudo systemctl reload nginx — no downtime
systemctl enable serviceEnable a service to start automatically at bootCreates symlinks in the appropriate systemd target directory
systemctl disable servicePrevent a service from starting at bootDoes not stop the currently running service
systemctl is-active serviceReturn whether a service is currently activeReturns active or inactive — useful in scripts
systemctl list-units --type=serviceList all loaded service units and their stateAdd --all to include inactive services
journalctl -u serviceShow all logs for a specific servicejournalctl -u nginx
journalctl -u service -fFollow live logs for a servicejournalctl -fu nginx
journalctl -u service --since "1 hour ago"Show logs from the last hour for a serviceAlso accepts: "2024-01-01 12:00:00", yesterday
journalctl -xeShow recent journal entries with context, jumping to the endFirst place to look after a failed service start
systemctl daemon-reloadReload systemd manager configurationRun after creating or editing a .service unit file in /etc/systemd/system/

SSH and Remote Access

CommandWhat it doesExample / Notes
ssh user@hostConnect to a remote host over SSHssh [email protected]
ssh -p 2222 user@hostConnect using a non-standard SSH portCommon when port 22 is remapped for security
ssh -i ~/.ssh/key user@hostConnect using a specific private keyKey must have permissions 600
ssh-keygen -t ed25519Generate a new ED25519 key pairPreferred over RSA for new keys; saves to ~/.ssh/ by default
ssh-copy-id user@hostCopy your public key to a remote host’s authorised keysEnables passwordless SSH login
scp file user@host:/pathSecurely copy a file to a remote hostscp backup.tar.gz ubuntu@nas:/backups/
scp -r dir user@host:/pathRecursively copy a directory to a remote hostUse rsync for large or resumable transfers
rsync -avz source/ user@host:/dest/Sync files to a remote host, showing progress-a archive, -v verbose, -z compress in transit
rsync -avz --delete source/ dest/Sync and delete files in destination not present in sourceUseful for backups; test without --delete first

SSH config shortcut

Create or edit ~/.ssh/config to define aliases for frequently accessed hosts:

Host myserver
    HostName 192.168.1.100
    User ubuntu
    IdentityFile ~/.ssh/id_ed25519
    Port 22

After saving, connect with simply ssh myserver.

Cron Jobs

Crontab commands

CommandWhat it doesExample / Notes
crontab -eEdit the current user’s crontabOpens in the default editor; set with EDITOR=nano crontab -e
crontab -lList the current user’s scheduled cron jobssudo crontab -l -u username to view another user’s crontab
crontab -rRemove the current user’s crontab entirelyIrreversible — back up with crontab -l > crontab.bak first

Cron syntax

# ┌───────────── minute (0–59)
# │ ┌─────────── hour (0–23)
# │ │ ┌───────── day of month (1–31)
# │ │ │ ┌─────── month (1–12)
# │ │ │ │ ┌───── day of week (0–7, Sunday = 0 or 7)
# │ │ │ │ │
# * * * * *  command to execute
ExpressionMeaning
0 2 * * *Every day at 02:00
*/15 * * * *Every 15 minutes
0 0 * * 0Every Sunday at midnight
0 9-17 * * 1-5Every hour from 09:00 to 17:00, Monday to Friday
30 4 1 * *At 04:30 on the first day of every month
@rebootOnce when the system boots
@dailyOnce per day (equivalent to 0 0 * * *)
@weeklyOnce per week (equivalent to 0 0 * * 0)
@monthlyOnce per month (equivalent to 0 0 1 * *)

Text Processing

CommandWhat it doesExample / Notes
grepSearch for lines matching a patterngrep -r "error" /var/log/ — search all logs for errors
sedStream editor for filtering and transforming textsed -i 's/old/new/g' file.txt — find and replace in place across entire file
awkPattern scanning and text processing languageawk '{print $1}' file — print the first field of each line
sortSort lines of textsort -n file — numeric sort; sort -r — reverse order
uniqRemove consecutive duplicate linessort file | uniq — sort first to ensure duplicates are adjacent
cutExtract sections from each line of a filecut -d',' -f2 file.csv — extract the second column from a CSV
trTranslate or delete characterscat file | tr '[:lower:]' '[:upper:]' — convert file contents to uppercase
wcCount lines, words, and characterswc -l file — line count; wc -w file — word count

Practical text processing one-liners

# Find and replace a string across a file
sed -i 's/oldstring/newstring/g' config.txt

# Print the third column from a space-delimited file
awk '{print $3}' access.log

# Show unique IP addresses from an Nginx access log
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn

# Remove blank lines from a file
sed -i '/^$/d' file.txt

# Extract the second field from a colon-delimited file
cut -d':' -f2 /etc/passwd

# Count how many times each HTTP status code appears in a log
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -rn

Archives and Compression

CommandWhat it doesExample / Notes
tar -czf archive.tar.gz /pathCreate a gzip-compressed tar archivetar -czf backup-$(date +%F).tar.gz /etc/nginx
tar -xzf archive.tar.gzExtract a gzip-compressed tar archiveAdd -C /dest/ to extract to a specific directory
tar -tzf archive.tar.gzList the contents of a tar.gz archive without extractingVerify contents before extracting
tar -cjf archive.tar.bz2 /pathCreate a bzip2-compressed tar archiveBetter compression than gzip but slower
zip -r archive.zip /pathCreate a zip archive recursivelyzip -r configs.zip /etc/nginx /etc/mysql
unzip archive.zipExtract a zip archiveunzip archive.zip -d /dest/ — extract to a specific directory
gzip fileCompress a single file with gzipReplaces the original file with file.gz
gunzip file.gzDecompress a gzip fileEquivalent to gzip -d file.gz
7z a archive.7z /pathCreate a 7-Zip archiveInstall with apt install p7zip-full; highest compression ratio
7z x archive.7zExtract a 7-Zip archive7z x archive.7z -o/dest/ — extract to a specific path

Useful One-Liners

# Check what's listening on a specific port
ss -tulpn | grep :80

# Find files larger than 1 GB
find / -type f -size +1G 2>/dev/null

# Watch a command refresh every 2 seconds
watch -n 2 df -h

# Tail multiple log files at once
tail -f /var/log/syslog /var/log/auth.log

# Count lines in a log file matching a pattern
grep -c "ERROR" /var/log/app.log

# Recursively find and delete files by extension
find /path -name "*.tmp" -delete

# Show the 10 largest directories
du -h --max-depth=1 / 2>/dev/null | sort -rh | head -10

# Check which process is using a specific port
lsof -i :8080

# Follow systemd logs for the Docker service
journalctl -fu docker

# Generate a random 32-character password
openssl rand -base64 32

# Show failed login attempts
grep "Failed password" /var/log/auth.log | awk '{print $11}' | sort | uniq -c | sort -rn

# Display real-time network interface statistics
watch -n 1 cat /proc/net/dev

# Find all SUID files (potential privilege escalation vectors)
find / -perm /4000 -type f 2>/dev/null

# Quickly test if a remote port is open (no nmap required)
timeout 3 bash -c 'cat < /dev/null > /dev/tcp/192.168.1.1/22' && echo "Open" || echo "Closed"

# Show disk I/O per process
iotop -o

# List the 10 most recently modified files in a directory
find /var/log -type f -printf '%T@ %p\n' | sort -rn | head -10 | awk '{print $2}'

# Reload shell configuration without logging out
source ~/.bashrc

# Show environment variables sorted alphabetically
env | sort

Related articles: n8n Expressions Cheat Sheet: Variables, Functions and Syntax, Proxmox Cheat Sheet: CLI Commands for VMs, LXC and Storage, Git Cheat Sheet: Every Command You Need, How to Revive an Old PC with Linux