~/linux-command-cheat-sheet
$

Linux Command Cheat Sheet

Searchable reference of essential Linux commands with examples. Filter by category, search by name, and copy commands instantly.

Showing 122 commands

lsList directory contents
List all files with details
ls -la
List sorted by size, human-readable
ls -lhS
List sorted by time with color
ls -lt --color=auto
cpCopy files and directories
Copy a file
cp file.txt backup.txt
Copy directory recursively
cp -r src/ dest/
Copy preserving attributes
cp -p file.txt /backup/
mvMove or rename files and directories
Rename a file
mv old.txt new.txt
Move file to directory
mv file.txt /target/dir/
Move with overwrite prompt
mv -i src dest
rmRemove files or directories
Remove a file
rm file.txt
Remove directory recursively
rm -rf directory/
Remove with confirmation prompt
rm -i *.log
mkdirCreate directories
Create a directory
mkdir new_dir
Create nested directories
mkdir -p parent/child/grandchild
Create with specific permissions
mkdir -m 755 secure_dir
rmdirRemove empty directories
Remove an empty directory
rmdir empty_dir
Remove nested empty directories
rmdir -p a/b/c
touchCreate empty files or update timestamps
Create an empty file
touch newfile.txt
Set specific timestamp
touch -t 202301011200 file.txt
Copy timestamp from another file
touch -r ref.txt target.txt
findSearch for files in a directory hierarchy
Find files by name
find / -name '*.conf'
Files modified in last 7 days
find . -type f -mtime -7
Find and delete files over 100MB
find . -size +100M -exec rm {} \;
locateFind files by name using a prebuilt database
Find a file quickly
locate nginx.conf
Case-insensitive search
locate -i README
chmodChange file permissions
Set rwxr-xr-x permissions
chmod 755 script.sh
Add execute permission
chmod +x script.sh
Recursively set permissions
chmod -R 644 /var/www/
chownChange file owner and group
Change owner and group
chown user:group file.txt
Recursive ownership change
chown -R www-data:www-data /var/www/
Copy ownership from reference
chown --reference=ref.txt target.txt
chgrpChange group ownership of files
Change group of a directory
chgrp developers project/
Recursively change group
chgrp -R staff /shared/
lnCreate hard and symbolic links
Create a symbolic link
ln -s /path/to/target link_name
Create a hard link
ln file.txt hardlink.txt
Force overwrite existing link
ln -sf /new/target link_name
statDisplay detailed file or filesystem status
Show file details
stat file.txt
Show filesystem info
stat -f /
fileDetermine file type
Identify a file type
file image.png
Show MIME type
file -i document.pdf
catConcatenate and display file contents
Display file contents
cat file.txt
Display with line numbers
cat -n file.txt
Concatenate files
cat file1.txt file2.txt > merged.txt
lessView file contents page by page
Browse a log file
less /var/log/syslog
View with line numbers
less -N file.txt
moreView file contents one screen at a time
View file page by page
more file.txt
Pipe command output to more
dmesg | more
headOutput the first part of files
Show first 20 lines
head -n 20 file.txt
Show first 100 bytes
head -c 100 file.txt
tailOutput the last part of files
Show last 50 lines
tail -n 50 file.txt
Follow log file in real time
tail -f /var/log/syslog
Follow until process exits
tail -f --pid=1234 logfile
grepSearch text using patterns
Search for a pattern
grep 'error' /var/log/syslog
Recursive case-insensitive search
grep -rni 'TODO' ./src/
Extended regex search
grep -E '^[0-9]+' file.txt
sedStream editor for text transformations
Replace all occurrences
sed 's/old/new/g' file.txt
Delete line 5 in-place
sed -i '5d' file.txt
Print lines 10 to 20
sed -n '10,20p' file.txt
awkPattern scanning and text processing language
Print columns 1 and 3
awk '{print $1, $3}' file.txt
Print usernames from passwd
awk -F: '{print $1}' /etc/passwd
Count matching lines
awk '/error/{count++} END{print count}' log
sortSort lines of text files
Sort alphabetically
sort file.txt
Sort numerically, reversed
sort -n -r numbers.txt
Sort CSV by second field
sort -t, -k2 data.csv
uniqReport or omit repeated lines
Remove duplicate lines
sort file.txt | uniq
Count occurrences
sort file.txt | uniq -c
Show only duplicates
sort file.txt | uniq -d
wcCount lines, words, and bytes
Count lines
wc -l file.txt
Count words
wc -w file.txt
Count Python files
find . -name '*.py' | wc -l
cutRemove sections from each line of files
Extract first field
cut -d: -f1 /etc/passwd
Extract first 10 characters
cut -c1-10 file.txt
trTranslate or delete characters
Convert to uppercase
echo 'hello' | tr a-z A-Z
Remove newlines
tr -d '\n' < file.txt
Squeeze repeated spaces
tr -s ' ' < file.txt
diffCompare files line by line
Compare two files
diff file1.txt file2.txt
Unified diff format
diff -u old.txt new.txt
Compare directories recursively
diff -r dir1/ dir2/
teeRead from stdin and write to stdout and files
Write to file and stdout
echo 'log entry' | tee output.log
Log build output
make 2>&1 | tee build.log
Append to file
echo 'line' | tee -a file.txt
unamePrint system information
Show all system info
uname -a
Show kernel version
uname -r
hostnameShow or set the system hostname
Display hostname
hostname
Show all IP addresses
hostname -I
uptimeShow how long the system has been running
Show uptime and load
uptime
Pretty-print uptime
uptime -p
whoamiPrint the current username
Show current user
whoami
idPrint user and group IDs
Show current user info
id
Show numeric user ID
id -u
Show info for a specific user
id username
dfReport filesystem disk space usage
Human-readable disk usage
df -h
Show filesystem types
df -T
Check specific mount point
df -h /home
duEstimate file space usage
Summarize sizes in current dir
du -sh *
Top-level directory sizes
du -h --max-depth=1 /var
Total size of a directory
du -sh /home/user/
freeDisplay memory usage
Human-readable memory usage
free -h
Memory in megabytes
free -m
topDisplay real-time process information
Interactive process viewer
top
Batch mode, single snapshot
top -bn1 | head -20
htopInteractive process viewer (enhanced top)
Launch interactive viewer
htop
Filter by user
htop -u username
lscpuDisplay CPU architecture information
Show CPU details
lscpu
Show CPU model
lscpu | grep 'Model name'
lsblkList block devices
Show all block devices
lsblk
Show filesystem information
lsblk -f
lsusbList USB devices
List all USB devices
lsusb
Verbose USB device info
lsusb -v
dmidecodeDMI/SMBIOS hardware information
Show RAM details
sudo dmidecode -t memory
Show BIOS info
sudo dmidecode -t bios
psReport a snapshot of current processes
Show all processes
ps aux
Find a specific process
ps aux | grep nginx
Show process tree
ps -ef --forest
killSend signals to processes
Terminate process by PID
kill 1234
Force kill a process
kill -9 1234
Send SIGHUP to reload
kill -HUP 1234
killallKill processes by name
Kill all Firefox processes
killall firefox
Force kill all python3
killall -9 python3
pkillSignal processes based on name and attributes
Kill by full command match
pkill -f 'node server'
Kill all processes by user
pkill -u username
niceRun a command with modified scheduling priority
Run with lower priority
nice -n 10 ./heavy_task.sh
Run with higher priority
nice -n -5 ./important.sh
reniceAlter priority of running processes
Lower priority of PID 1234
renice +10 -p 1234
Raise priority for a user
renice -5 -u username
nohupRun a command immune to hangups
Run in background, persist after logout
nohup ./script.sh &
With custom log file
nohup ./script.sh > output.log 2>&1 &
bgResume a suspended job in the background
Resume job 1 in background
bg %1
fgBring a background job to the foreground
Bring job 1 to foreground
fg %1
jobsList active jobs in the current shell
List all jobs
jobs
List jobs with PIDs
jobs -l
&Run a command in the background
Start process in background
./long_task.sh &
Background chained commands
sleep 60 && echo done &
waitWait for background processes to finish
Wait for all background jobs
wait
Wait for specific PID
wait 1234
ipShow/manipulate routing, devices, and tunnels
Show all IP addresses
ip addr show
Show routing table
ip route show
Bring interface up
ip link set eth0 up
ifconfigConfigure network interfaces (legacy)
Show all interfaces
ifconfig
Set IP address
ifconfig eth0 192.168.1.10 netmask 255.255.255.0
pingSend ICMP echo requests to hosts
Ping with 4 packets
ping -c 4 google.com
Ping every 0.5 seconds
ping -i 0.5 192.168.1.1
tracerouteTrace the route to a network host
Trace route to host
traceroute google.com
Trace without DNS resolution
traceroute -n 8.8.8.8
netstatNetwork statistics (legacy, use ss)
Show listening TCP ports
netstat -tlnp
Show all connections
netstat -an
ssSocket statistics (modern netstat replacement)
Show listening TCP ports
ss -tlnp
Show socket summary
ss -s
Show established connections
ss -tp state established
curlTransfer data from or to a server
Fetch HTTP headers
curl -I https://example.com
Download a file
curl -O https://example.com/file.tar.gz
POST JSON data
curl -X POST -d '{"key":"val"}' -H 'Content-Type: application/json' http://api/endpoint
wgetNon-interactive network downloader
Download a file
wget https://example.com/file.tar.gz
Recursive download
wget -r -np https://example.com/docs/
Resume interrupted download
wget -c https://example.com/large.iso
digDNS lookup utility
Query DNS records
dig example.com
Get A record only
dig +short example.com A
Query specific DNS server
dig @8.8.8.8 example.com MX
nslookupQuery DNS name servers
Basic DNS lookup
nslookup example.com
Query MX records
nslookup -type=MX example.com
nmapNetwork exploration and port scanner
Scan with service detection
nmap -sV 192.168.1.1
Scan port range on subnet
nmap -p 1-1000 192.168.1.0/24
Aggressive scan (OS, version, scripts)
nmap -A target.com
iptablesIPv4 packet filter and NAT administration
List all rules
iptables -L -n -v
Allow HTTP traffic
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
Block a subnet
iptables -A INPUT -s 10.0.0.0/8 -j DROP
ufwUncomplicated firewall frontend for iptables
Enable the firewall
ufw enable
Allow SSH
ufw allow 22/tcp
Show firewall status
ufw status verbose
useraddCreate a new user account
Create user with home dir
useradd -m -s /bin/bash newuser
Create user with groups
useradd -G sudo,docker newuser
userdelDelete a user account
Delete a user
userdel username
Delete user and home directory
userdel -r username
usermodModify a user account
Add user to group
usermod -aG docker username
Change user shell
usermod -s /bin/zsh username
Lock a user account
usermod -L username
passwdChange user password
Change own password
passwd
Change another user's password
passwd username
Force password change on next login
passwd -e username
groupaddCreate a new group
Create a new group
groupadd developers
Create group with specific GID
groupadd -g 1500 custom
groupsShow group memberships
Show current user's groups
groups
Show groups for a user
groups username
suSwitch user identity
Switch to user with login shell
su - username
Run command as another user
su -c 'command' username
sudoExecute a command as another user (typically root)
Run as root
sudo command
Run as specific user
sudo -u www-data command
Open root shell
sudo -i
visudoSafely edit the sudoers file
Edit sudoers safely
sudo visudo
Edit a sudoers drop-in file
sudo visudo -f /etc/sudoers.d/custom
aptDebian/Ubuntu package manager
Update all packages
sudo apt update && sudo apt upgrade
Install a package
sudo apt install nginx
Search for packages
apt search keyword
yumRHEL/CentOS package manager (legacy)
Install a package
sudo yum install httpd
List installed packages
yum list installed
dnfFedora/RHEL 8+ package manager
Install a package
sudo dnf install nginx
Search for packages
dnf search keyword
Upgrade all packages
sudo dnf upgrade --refresh
pacmanArch Linux package manager
Full system upgrade
sudo pacman -Syu
Install a package
sudo pacman -S package
Search for packages
pacman -Ss keyword
apkAlpine Linux package manager
Install a package
apk add nginx
Update all packages
apk update && apk upgrade
snapSnap package manager
Install a snap
sudo snap install code --classic
List installed snaps
snap list
flatpakFlatpak application manager
Install from Flathub
flatpak install flathub org.gimp.GIMP
List installed apps
flatpak list
dpkgLow-level Debian package manager
Install a .deb file
sudo dpkg -i package.deb
Check if package is installed
dpkg -l | grep nginx
rpmLow-level RPM package manager
Install an RPM
sudo rpm -ivh package.rpm
Query installed packages
rpm -qa | grep httpd
mountMount a filesystem
Mount a device
mount /dev/sdb1 /mnt/usb
Mount an ISO file
mount -o loop image.iso /mnt/iso
List all mounts formatted
mount | column -t
umountUnmount a filesystem
Unmount a device
umount /mnt/usb
Lazy unmount (when busy)
umount -l /mnt/busy
fdiskPartition table manipulator
List all partitions
sudo fdisk -l
Partition a disk interactively
sudo fdisk /dev/sdb
mkfsBuild a Linux filesystem
Create ext4 filesystem
sudo mkfs.ext4 /dev/sdb1
Create XFS filesystem
sudo mkfs.xfs /dev/sdb1
lsblkList information about block devices
Show block devices tree
lsblk
Show filesystems and UUIDs
lsblk -f
blkidLocate/print block device attributes
Show all device UUIDs
blkid
Show UUID for a device
blkid /dev/sda1
ddConvert and copy a file (low-level)
Create disk image
dd if=/dev/sda of=backup.img bs=4M status=progress
Write ISO to USB
dd if=ubuntu.iso of=/dev/sdb bs=4M status=progress
rsyncFast, versatile file copying tool
Sync directories locally
rsync -avz src/ dest/
Sync to remote server
rsync -avz -e ssh /local/ user@host:/remote/
Mirror with deletion
rsync -avz --delete src/ dest/
scpSecure copy over SSH
Copy file to remote
scp file.txt user@host:/path/
Copy directory from remote
scp -r user@host:/remote/dir/ ./local/
tarArchive utility
Create gzipped archive
tar -czvf archive.tar.gz /path/to/dir
Extract gzipped archive
tar -xzvf archive.tar.gz
List archive contents
tar -tf archive.tar.gz
gzipCompress files with gzip
Compress a file
gzip file.txt
Compress, keep original
gzip -k file.txt
Maximum compression
gzip -9 file.txt
gunzipDecompress gzip files
Decompress a file
gunzip file.txt.gz
bzip2Compress files with bzip2
Compress a file
bzip2 file.txt
Decompress, keep original
bzip2 -dk file.txt.bz2
xzCompress files with xz (high ratio)
Compress a file
xz file.txt
Decompress, keep original
xz -dk file.txt.xz
zipPackage and compress files
Create a zip archive
zip archive.zip file1.txt file2.txt
Zip a directory
zip -r archive.zip directory/
unzipExtract zip archives
Extract zip archive
unzip archive.zip
Extract to specific directory
unzip archive.zip -d /target/dir/
List archive contents
unzip -l archive.zip
7z7-Zip file archiver (high compression)
Create 7z archive
7z a archive.7z files/
Extract 7z archive
7z x archive.7z
sshSecure shell remote login
Connect to remote host
ssh user@hostname
Connect on custom port
ssh -p 2222 user@hostname
Local port forwarding
ssh -L 8080:localhost:80 user@host
scpSecure copy files over SSH
Upload a file
scp file.txt user@host:/path/
Download a file
scp user@host:/remote/file.txt ./
rsyncRemote file synchronization over SSH
Sync to remote
rsync -avz -e ssh local/ user@host:/remote/
Sync from remote
rsync -avz user@host:/remote/ ./local/
sftpSecure FTP over SSH
Start SFTP session
sftp user@hostname
SFTP on custom port
sftp -P 2222 user@hostname
ssh-keygenGenerate SSH key pairs
Generate Ed25519 key
ssh-keygen -t ed25519 -C '[email protected]'
Generate 4096-bit RSA key
ssh-keygen -t rsa -b 4096
ssh-copy-idCopy SSH public key to a remote host
Install key on remote
ssh-copy-id user@hostname
Specify key file
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@host
ssh-agentSSH authentication agent
Start the SSH agent
eval $(ssh-agent -s)
Add key to agent
ssh-add ~/.ssh/id_ed25519
systemctlControl systemd services and units
Check service status
systemctl status nginx
Start a service
systemctl start nginx
Enable and start service
systemctl enable --now nginx
journalctlQuery the systemd journal
Recent logs for a service
journalctl -u nginx --since '1 hour ago'
Follow logs in real time
journalctl -f
Errors since last boot
journalctl -p err -b
timedatectlControl system time and date
Show current time settings
timedatectl
Set timezone
timedatectl set-timezone America/New_York
hostnamectlControl the system hostname
Show hostname info
hostnamectl
Set hostname
hostnamectl set-hostname webserver
loginctlControl the systemd login manager
List active sessions
loginctl list-sessions
Show user session info
loginctl show-user username
docker runCreate and start a container
Run nginx in background
docker run -d -p 80:80 nginx
Interactive disposable container
docker run -it --rm ubuntu bash
With volume and env var
docker run -v /host:/container -e VAR=val image
docker psList running containers
Show running containers
docker ps
Show all containers
docker ps -a
Custom format output
docker ps --format 'table {{.Names}}\t{{.Status}}'
docker buildBuild an image from a Dockerfile
Build and tag image
docker build -t myapp:latest .
Build without cache
docker build --no-cache -t myapp .
Use specific Dockerfile
docker build -f Dockerfile.prod -t myapp:prod .
docker execRun a command in a running container
Open shell in container
docker exec -it container_name bash
Run a command
docker exec container_name ls /app
docker logsFetch logs from a container
View container logs
docker logs container_name
Follow last 100 lines
docker logs -f --tail 100 container_name
docker-composeDefine and run multi-container applications
Start services in background
docker-compose up -d
Stop and remove volumes
docker-compose down -v
Follow service logs
docker-compose logs -f service_name