Skip to main content

Linux Command Cheat Sheet

A comprehensive reference for essential Linux commands organized by function. Master file operations, process management, networking, system administration, and more.


1. Navigation & File System

CommandDescription
pwdPrint working directory
lsList directory contents
ls -laList with hidden files and full details
ls -lhList with human-readable file sizes
ls -ltList sorted by modification time
cdChange directory
cd ~Change to home directory
cd -Change to previous directory
cd /Change to root directory
mkdirCreate a directory
mkdir -pCreate directories recursively
rmdirRemove empty directory
cpCopy file or directory
cp -rCopy directory recursively
cp -vCopy with verbose output
mvMove or rename file/directory
rmRemove file
rm -rRemove directory recursively
rm -fForce remove without confirmation
touchCreate empty file or update timestamp
findSearch for files by name, type, size, etc.
find . -name "*.txt"Find all .txt files in current directory
find / -size +100MFind files larger than 100MB
locateFind files by name (fast, uses database)
updatedbUpdate locate database
treeDisplay directory structure as tree
tree -L 2Show tree with depth limit 2
lnCreate hard link
ln -sCreate symbolic link
readlinkDisplay target of symbolic link
statDisplay file/directory statistics
fileDetermine file type
basenameGet filename from path
dirnameGet directory path from full path

2. File Viewing & Editing

CommandDescription
catDisplay file contents
cat file1 file2Concatenate multiple files
headShow first 10 lines
head -n 20Show first 20 lines
tailShow last 10 lines
tail -fFollow file (watch updates)
lessView file with pagination
moreView file with pagination (less advanced)
nanoSimple text editor
vi or vimAdvanced text editor
vim -u NONEOpen vim without configuration
teeRead from stdin and write to file and stdout
wcCount words, lines, characters
wc -lCount lines only
nlDisplay file with line numbers
odDump file in octal/hex format
hexdumpDisplay file in hexadecimal
xxdCreate hex dumps or convert hex to binary

3. Text Processing

CommandDescription
grepSearch for pattern in files
grep -iCase-insensitive search
grep -rSearch recursively in directories
grep -vInvert match (show non-matching lines)
grep -nShow line numbers
grep -EUse extended regex
egrepExtended grep (equivalent to grep -E)
fgrepFixed string search (no regex)
sedStream editor for filtering/transforming text
sed 's/old/new/'Replace first occurrence on each line
sed 's/old/new/g'Replace all occurrences
sed -n '5,10p'Print lines 5-10
sed '10d'Delete line 10
awkText processing and pattern scanning
awk '{print $1}'Print first column
awk -F:Set field separator
sortSort lines
sort -nNumeric sort
sort -rReverse sort
sort -uSort and remove duplicates
uniqRemove duplicate consecutive lines
uniq -cCount duplicate lines
cutExtract columns from text
cut -d: -f1Extract field 1 with : separator
trTranslate or delete characters
tr 'a-z' 'A-Z'Convert lowercase to uppercase
pasteMerge lines from files
joinJoin lines based on common field
diffShow differences between files
diff -uUnified diff format
commCompare sorted files line by line
xargsBuild and execute command from input
fmtFormat text paragraphs
columnFormat text into columns
column -tAlign text as table

4. Permissions & Ownership

CommandDescription
chmodChange file/directory permissions
chmod 755rwxr-xr-x
chmod 644rw-r--r--
chmod u+xAdd execute for owner
chmod g-rRemove read from group
chmod a+rAdd read for all
chownChange file owner
chown user:groupChange owner and group
chown -RChange ownership recursively
chgrpChange group ownership
umaskSet default permissions for new files
getfaclDisplay ACL permissions
setfaclSet ACL permissions
chattrChange file attributes (immutable, etc.)
chattr +iMake file immutable
chattr -iRemove immutable attribute
lsattrList file attributes

5. User & Group Management

CommandDescription
useraddCreate new user
useradd -mCreate user with home directory
useradd -s /bin/bashSpecify login shell
userdelDelete user
userdel -rDelete user and home directory
usermodModify user account
usermod -aG group userAdd user to group
usermod -d /home/newdirChange home directory
usermod -s /bin/zshChange login shell
groupaddCreate new group
groupdelDelete group
groupmodModify group
passwdChange user password
passwd -lLock user account
passwd -uUnlock user account
whoamiDisplay current user
idDisplay user/group IDs
id usernameShow info for specific user
whoList logged-in users
wShow logged-in users and what they're doing
lastShow login history
lastlogShow recent login information
suSwitch user
su -Switch user with login shell
sudoExecute as superuser
sudo -iOpen root shell
sudo -u userExecute as specific user
visudoEdit sudoers file safely
fingerDisplay user information
finger usernameGet info about specific user

6. Process Management

CommandDescription
psDisplay processes
ps auxShow all processes with details
ps aux | grep nameFind process by name
ps -efFull format process listing
ps -eo pid,user,cpu,mem,commCustom output format
topInteractive process monitor
top -u userMonitor processes for specific user
htopEnhanced process monitor
atopAdvanced system monitor
killTerminate process by PID
kill -9Force kill process
kill -TERMGraceful termination
killallTerminate processes by name
killall -9Force kill all processes by name
pkillKill processes matching pattern
pkill -f commandKill by full command match
niceStart process with priority
nice -n 10 commandLower priority (higher is less important)
reniceChange process priority
renice -n 5 -p PIDAdjust priority of running process
bgResume suspended job in background
fgBring background job to foreground
jobsList background/suspended jobs
nohupRun command immune to hangups
nohup command &Run in background and log to nohup.out
screenTerminal multiplexer/session manager
tmuxTerminal multiplexer (modern alternative)
pgrepFind processes by name/pattern
pgrep -lShow process name and PID

7. Networking

CommandDescription
ip addrShow IP addresses
ip addr showDisplay all interfaces
ip addr add IP/MASK dev eth0Add IP address
ip linkShow link layer information
ip link set eth0 upBring interface up
ip link set eth0 downBring interface down
ifconfigLegacy network interface config (deprecated)
ifconfig eth0Show specific interface
ssSocket statistics (modern netstat replacement)
ss -tlnpShow listening TCP ports with processes
ss -ulnpShow listening UDP ports with processes
netstatNetwork statistics (legacy)
netstat -tlnpShow listening ports
netstat -anShow all connections
pingTest connectivity to host
ping -c 4Send 4 pings
tracerouteTrace route to host
tracepathTrace path (doesn't need root)
mtrNetwork diagnostic tool (ping + traceroute)
digDNS query tool
dig example.comQuery A record
dig +shortShort answer only
dig @8.8.8.8Query specific nameserver
nslookupQuery DNS (simpler than dig)
hostSimple DNS lookup
curlTransfer data with URLs
curl -IFetch headers only
curl -X POST -d dataMake POST request
wgetDownload files from web
wget -O filenameSave with specific name
wget -rDownload recursively
scpSecure copy between hosts
scp file user@host:/path/Copy file to remote
rsyncSynchronize files between systems
rsync -avzVerbose, archive, compressed
sshSecure shell connection
ssh -i key.pem user@hostConnect with specific key
ssh -L 8000:localhost:3000Local port forwarding
ssh -R 8000:localhost:3000Remote port forwarding
ssh -D 1080Dynamic proxy (SOCKS)
ncNetcat - network utility
nc -l -p 5000Listen on port 5000
nc -zv host portCheck if port is open
tcpdumpPacket sniffer
tcpdump -i eth0Capture on specific interface
tcpdump -nDon't resolve DNS
nmapNetwork scanner
nmap -sn 192.168.1.0/24Scan network for hosts
nmap -p 80,443Scan specific ports
telnetTelnet client (insecure)
hostnameDisplay system hostname
hostname -IShow all IP addresses
hostnamectlManage system hostname
routeShow routing table
route -nNumeric (no DNS resolution)
arpAddress resolution protocol table
arp -aShow ARP cache

8. Disk & Storage

CommandDescription
dfDisk free space
df -hHuman-readable format
df -TShow filesystem type
duDisk usage of directories
du -shSummary in human-readable format
du -sh *Size of each item in directory
du -sh * | sort -hShow sizes sorted
lsblkList block devices
blkidShow block device IDs/UUIDs
fdiskPartition table manipulator
fdisk -lList partitions
partedGNU Parted partition editor
mountMount filesystem
mount /dev/sda1 /mnt/Mount device to mountpoint
umountUnmount filesystem
umount /mnt/Unmount directory
mkfsCreate filesystem
mkfs.ext4Create ext4 filesystem
mkfs.vfatCreate FAT filesystem
fsckFilesystem check and repair
e2fsckCheck ext filesystem
fstabStatic filesystem mount table (/etc/fstab)
ddCopy and convert data
dd if=/dev/zero of=file bs=1M count=100Create 100MB file
dd if=/dev/sda of=backup.imgDisk backup

9. Archive & Compression

CommandDescription
tarArchive files
tar -cvf archive.tar files/Create archive
tar -xvf archive.tarExtract archive
tar -tf archive.tarList contents
tar -czf archive.tar.gz files/Create gzip compressed
tar -xzf archive.tar.gzExtract gzip
tar -cjf archive.tar.bz2 files/Create bzip2 compressed
tar -xjf archive.tar.bz2Extract bzip2
gzipCompress file
gzip fileCreates file.gz
gunzipDecompress gzip
bzip2Compress with bzip2
bunzip2Decompress bzip2
xzCompress with xz
unxzDecompress xz
zipZIP archive
zip -r archive.zip folder/Zip directory recursively
unzipExtract ZIP
unzip -lList ZIP contents
7z7-Zip archive tool
zcatView compressed file contents
zgrepGrep in compressed file

10. System Information

CommandDescription
unameSystem information
uname -aAll system information
uname -rKernel release/version
uname -mMachine hardware name (x86_64)
lsb_release -aLinux distribution version
cat /etc/os-releaseOS information
hostnameSystem hostname
uptimeSystem uptime and load
dateCurrent date and time
calCalendar
freeMemory usage
free -hHuman-readable format
free -mMemory in megabytes
lscpuCPU information
lspciPCI devices (graphics cards, etc.)
lsusbUSB devices
dmesgKernel messages
dmesg | tailLatest kernel messages
journalctlSystem journal logs
journalctl -xeRecent errors
timedatectlTime and date settings
timedatectl set-timezoneSet timezone
hwinfoDetailed hardware information
inxiSystem information summary

11. Service Management

CommandDescription
systemctlControl systemd services
systemctl status serviceCheck service status
systemctl start serviceStart service
systemctl stop serviceStop service
systemctl restart serviceRestart service
systemctl reload serviceReload configuration
systemctl enable serviceEnable service at boot
systemctl disable serviceDisable service at boot
systemctl list-unitsList all units
systemctl list-units --failedShow failed units
journalctl -u serviceView service logs
journalctl -u service -fFollow service logs

12. Package Management

CommandDescription
aptDebian/Ubuntu package manager
apt updateUpdate package lists
apt upgradeUpgrade packages
apt install packageInstall package
apt remove packageRemove package
apt search packageSearch for package
apt list --upgradableShow upgradable packages
yumRedHat/CentOS package manager
yum install packageInstall on RHEL/CentOS
yum updateUpdate packages
dnfModern Fedora package manager
dnf install packageInstall on Fedora
pacmanArch Linux package manager
pacman -S packageInstall on Arch
apkAlpine Linux package manager
apk add packageInstall on Alpine
rpmRed Hat Package Manager
rpm -i package.rpmInstall RPM
rpm -qaQuery all installed packages
dpkgDebian package manager
dpkg -lList installed packages
dpkg -i package.debInstall DEB
snapUniversal package manager
snap install appInstall snap application

13. Shell Scripting Essentials

CommandDescription
echoPrint text
echo -nPrint without newline
echo -eEnable escape sequences
echo $VARPrint variable value
readRead user input
read -p "prompt" varPrompt and read into variable
testEvaluate condition (same as [)
[ -f file ]Test if file exists
[ -d dir ]Test if directory exists
[ -z string ]Test if string is empty
[ $a -eq $b ]Numeric equality
[ $a -lt $b ]Less than
[[ $str =~ pattern ]]Regex match
if then fiConditional statement
if then else fiIf-else statement
if then elif then fiIf-elif-else
for var in list; do doneFor loop
for ((i=0; i less than 10; i++)); do doneC-style for loop
while condition; do doneWhile loop
case $var in pattern) ;; esacSwitch statement
function name() { }Define function
$0, $1, $2Script name and arguments
$#Number of arguments
$@All arguments as array
$?Exit code of last command
exit 0Exit with code 0 (success)
trap 'cleanup' EXITRun command on exit/signal

14. Useful One-Liners

File Operations

# Find largest files in current directory
find . -type f -exec ls -lh {} \; | sort -k5 -rh | head -10

# Find files modified in last 7 days
find . -type f -mtime -7

# Find duplicate files
find . -type f -exec md5sum {} \; | sort | uniq -d

# Count all lines in all files in directory
find . -type f -name "*.txt" -exec wc -l {} + | tail -1

# Recursively search for string in files
grep -r "search_term" /path/to/search

# Replace string in all files in directory
find . -type f -name "*.txt" -exec sed -i 's/old/new/g' {} \;

Monitoring & Processes

# Monitor log file in real-time
tail -f /var/log/syslog

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

# Check all open ports and processes
netstat -tulnp | grep LISTEN

# Show CPU and memory usage by process
ps aux --sort=-%cpu | head -10
ps aux --sort=-%mem | head -10

# Monitor directory for changes
watch -n 2 'ls -lah /path/to/dir'

Network

# Check if port is open
nc -zv hostname port

# Quick DNS lookup
dig +short example.com

# Find all hosts on network
nmap -sn 192.168.1.0/24

# Show current network connections
ss -tan | grep ESTABLISHED

System Administration

# Show disk usage by directory (top 10)
du -sh */ | sort -rh | head -10

# List files by size in current directory
ls -lhS

# Count files in directory
find . -type f | wc -l

# Show system load average
uptime

# Display top resource consumers
top -b -n 1 | head -20

Text Processing

# Extract column from CSV
awk -F',' '{print $1, $3}' file.csv

# Sort and count occurrences
sort | uniq -c | sort -rn

# Remove duplicates while preserving order
awk '!seen[$0]++' file.txt

# Print specific lines
sed -n '10,20p' file.txt

# Split large file into parts
split -l 1000 largefile.txt part_

# Merge sorted files
sort -m file1.txt file2.txt file3.txt

Quick Reference by Task

Need to find something?

  • find - Comprehensive file search
  • locate - Quick file search (uses database)
  • grep - Search within files

Need to view/edit files?

  • cat - Quick view
  • less - Scroll through large files
  • nano - Simple editor
  • vim - Powerful editor

Need to manage processes?

  • ps - List processes
  • top / htop - Interactive monitor
  • kill - Terminate process
  • bg / fg - Background/foreground

Need to check system?

  • df - Disk space
  • free - Memory usage
  • top - CPU/memory
  • systemctl - Service status

Need to manage users?

  • useradd / userdel - Create/delete users
  • passwd - Change passwords
  • chmod / chown - Permissions/ownership

Need to work with archives?

  • tar - Most common
  • zip / unzip - ZIP format
  • gzip / gunzip - Gzip compression