$
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 contentsList all files with details
ls -laList sorted by size, human-readable
ls -lhSList sorted by time with color
ls -lt --color=autocpCopy files and directoriesCopy a file
cp file.txt backup.txtCopy directory recursively
cp -r src/ dest/Copy preserving attributes
cp -p file.txt /backup/mvMove or rename files and directoriesRename a file
mv old.txt new.txtMove file to directory
mv file.txt /target/dir/Move with overwrite prompt
mv -i src destrmRemove files or directoriesRemove a file
rm file.txtRemove directory recursively
rm -rf directory/Remove with confirmation prompt
rm -i *.logmkdirCreate directoriesCreate a directory
mkdir new_dirCreate nested directories
mkdir -p parent/child/grandchildCreate with specific permissions
mkdir -m 755 secure_dirrmdirRemove empty directoriesRemove an empty directory
rmdir empty_dirRemove nested empty directories
rmdir -p a/b/ctouchCreate empty files or update timestampsCreate an empty file
touch newfile.txtSet specific timestamp
touch -t 202301011200 file.txtCopy timestamp from another file
touch -r ref.txt target.txtfindSearch for files in a directory hierarchyFind files by name
find / -name '*.conf'Files modified in last 7 days
find . -type f -mtime -7Find and delete files over 100MB
find . -size +100M -exec rm {} \;locateFind files by name using a prebuilt databaseFind a file quickly
locate nginx.confCase-insensitive search
locate -i READMEchmodChange file permissionsSet rwxr-xr-x permissions
chmod 755 script.shAdd execute permission
chmod +x script.shRecursively set permissions
chmod -R 644 /var/www/chownChange file owner and groupChange owner and group
chown user:group file.txtRecursive ownership change
chown -R www-data:www-data /var/www/Copy ownership from reference
chown --reference=ref.txt target.txtchgrpChange group ownership of filesChange group of a directory
chgrp developers project/Recursively change group
chgrp -R staff /shared/lnCreate hard and symbolic linksCreate a symbolic link
ln -s /path/to/target link_nameCreate a hard link
ln file.txt hardlink.txtForce overwrite existing link
ln -sf /new/target link_namestatDisplay detailed file or filesystem statusShow file details
stat file.txtShow filesystem info
stat -f /fileDetermine file typeIdentify a file type
file image.pngShow MIME type
file -i document.pdfcatConcatenate and display file contentsDisplay file contents
cat file.txtDisplay with line numbers
cat -n file.txtConcatenate files
cat file1.txt file2.txt > merged.txtlessView file contents page by pageBrowse a log file
less /var/log/syslogView with line numbers
less -N file.txtmoreView file contents one screen at a timeView file page by page
more file.txtPipe command output to more
dmesg | moreheadOutput the first part of filesShow first 20 lines
head -n 20 file.txtShow first 100 bytes
head -c 100 file.txttailOutput the last part of filesShow last 50 lines
tail -n 50 file.txtFollow log file in real time
tail -f /var/log/syslogFollow until process exits
tail -f --pid=1234 logfilegrepSearch text using patternsSearch for a pattern
grep 'error' /var/log/syslogRecursive case-insensitive search
grep -rni 'TODO' ./src/Extended regex search
grep -E '^[0-9]+' file.txtsedStream editor for text transformationsReplace all occurrences
sed 's/old/new/g' file.txtDelete line 5 in-place
sed -i '5d' file.txtPrint lines 10 to 20
sed -n '10,20p' file.txtawkPattern scanning and text processing languagePrint columns 1 and 3
awk '{print $1, $3}' file.txtPrint usernames from passwd
awk -F: '{print $1}' /etc/passwdCount matching lines
awk '/error/{count++} END{print count}' logsortSort lines of text filesSort alphabetically
sort file.txtSort numerically, reversed
sort -n -r numbers.txtSort CSV by second field
sort -t, -k2 data.csvuniqReport or omit repeated linesRemove duplicate lines
sort file.txt | uniqCount occurrences
sort file.txt | uniq -cShow only duplicates
sort file.txt | uniq -dwcCount lines, words, and bytesCount lines
wc -l file.txtCount words
wc -w file.txtCount Python files
find . -name '*.py' | wc -lcutRemove sections from each line of filesExtract first field
cut -d: -f1 /etc/passwdExtract first 10 characters
cut -c1-10 file.txttrTranslate or delete charactersConvert to uppercase
echo 'hello' | tr a-z A-ZRemove newlines
tr -d '\n' < file.txtSqueeze repeated spaces
tr -s ' ' < file.txtdiffCompare files line by lineCompare two files
diff file1.txt file2.txtUnified diff format
diff -u old.txt new.txtCompare directories recursively
diff -r dir1/ dir2/teeRead from stdin and write to stdout and filesWrite to file and stdout
echo 'log entry' | tee output.logLog build output
make 2>&1 | tee build.logAppend to file
echo 'line' | tee -a file.txtunamePrint system informationShow all system info
uname -aShow kernel version
uname -rhostnameShow or set the system hostnameDisplay hostname
hostnameShow all IP addresses
hostname -IuptimeShow how long the system has been runningShow uptime and load
uptimePretty-print uptime
uptime -pwhoamiPrint the current usernameShow current user
whoamiidPrint user and group IDsShow current user info
idShow numeric user ID
id -uShow info for a specific user
id usernamedfReport filesystem disk space usageHuman-readable disk usage
df -hShow filesystem types
df -TCheck specific mount point
df -h /homeduEstimate file space usageSummarize sizes in current dir
du -sh *Top-level directory sizes
du -h --max-depth=1 /varTotal size of a directory
du -sh /home/user/freeDisplay memory usageHuman-readable memory usage
free -hMemory in megabytes
free -mtopDisplay real-time process informationInteractive process viewer
topBatch mode, single snapshot
top -bn1 | head -20htopInteractive process viewer (enhanced top)Launch interactive viewer
htopFilter by user
htop -u usernamelscpuDisplay CPU architecture informationShow CPU details
lscpuShow CPU model
lscpu | grep 'Model name'lsblkList block devicesShow all block devices
lsblkShow filesystem information
lsblk -flsusbList USB devicesList all USB devices
lsusbVerbose USB device info
lsusb -vdmidecodeDMI/SMBIOS hardware informationShow RAM details
sudo dmidecode -t memoryShow BIOS info
sudo dmidecode -t biospsReport a snapshot of current processesShow all processes
ps auxFind a specific process
ps aux | grep nginxShow process tree
ps -ef --forestkillSend signals to processesTerminate process by PID
kill 1234Force kill a process
kill -9 1234Send SIGHUP to reload
kill -HUP 1234killallKill processes by nameKill all Firefox processes
killall firefoxForce kill all python3
killall -9 python3pkillSignal processes based on name and attributesKill by full command match
pkill -f 'node server'Kill all processes by user
pkill -u usernameniceRun a command with modified scheduling priorityRun with lower priority
nice -n 10 ./heavy_task.shRun with higher priority
nice -n -5 ./important.shreniceAlter priority of running processesLower priority of PID 1234
renice +10 -p 1234Raise priority for a user
renice -5 -u usernamenohupRun a command immune to hangupsRun 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 backgroundResume job 1 in background
bg %1fgBring a background job to the foregroundBring job 1 to foreground
fg %1jobsList active jobs in the current shellList all jobs
jobsList jobs with PIDs
jobs -l&Run a command in the backgroundStart process in background
./long_task.sh &Background chained commands
sleep 60 && echo done &waitWait for background processes to finishWait for all background jobs
waitWait for specific PID
wait 1234ipShow/manipulate routing, devices, and tunnelsShow all IP addresses
ip addr showShow routing table
ip route showBring interface up
ip link set eth0 upifconfigConfigure network interfaces (legacy)Show all interfaces
ifconfigSet IP address
ifconfig eth0 192.168.1.10 netmask 255.255.255.0pingSend ICMP echo requests to hostsPing with 4 packets
ping -c 4 google.comPing every 0.5 seconds
ping -i 0.5 192.168.1.1tracerouteTrace the route to a network hostTrace route to host
traceroute google.comTrace without DNS resolution
traceroute -n 8.8.8.8netstatNetwork statistics (legacy, use ss)Show listening TCP ports
netstat -tlnpShow all connections
netstat -anssSocket statistics (modern netstat replacement)Show listening TCP ports
ss -tlnpShow socket summary
ss -sShow established connections
ss -tp state establishedcurlTransfer data from or to a serverFetch HTTP headers
curl -I https://example.comDownload a file
curl -O https://example.com/file.tar.gzPOST JSON data
curl -X POST -d '{"key":"val"}' -H 'Content-Type: application/json' http://api/endpointwgetNon-interactive network downloaderDownload a file
wget https://example.com/file.tar.gzRecursive download
wget -r -np https://example.com/docs/Resume interrupted download
wget -c https://example.com/large.isodigDNS lookup utilityQuery DNS records
dig example.comGet A record only
dig +short example.com AQuery specific DNS server
dig @8.8.8.8 example.com MXnslookupQuery DNS name serversBasic DNS lookup
nslookup example.comQuery MX records
nslookup -type=MX example.comnmapNetwork exploration and port scannerScan with service detection
nmap -sV 192.168.1.1Scan port range on subnet
nmap -p 1-1000 192.168.1.0/24Aggressive scan (OS, version, scripts)
nmap -A target.comiptablesIPv4 packet filter and NAT administrationList all rules
iptables -L -n -vAllow HTTP traffic
iptables -A INPUT -p tcp --dport 80 -j ACCEPTBlock a subnet
iptables -A INPUT -s 10.0.0.0/8 -j DROPufwUncomplicated firewall frontend for iptablesEnable the firewall
ufw enableAllow SSH
ufw allow 22/tcpShow firewall status
ufw status verboseuseraddCreate a new user accountCreate user with home dir
useradd -m -s /bin/bash newuserCreate user with groups
useradd -G sudo,docker newuseruserdelDelete a user accountDelete a user
userdel usernameDelete user and home directory
userdel -r usernameusermodModify a user accountAdd user to group
usermod -aG docker usernameChange user shell
usermod -s /bin/zsh usernameLock a user account
usermod -L usernamepasswdChange user passwordChange own password
passwdChange another user's password
passwd usernameForce password change on next login
passwd -e usernamegroupaddCreate a new groupCreate a new group
groupadd developersCreate group with specific GID
groupadd -g 1500 customgroupsShow group membershipsShow current user's groups
groupsShow groups for a user
groups usernamesuSwitch user identitySwitch to user with login shell
su - usernameRun command as another user
su -c 'command' usernamesudoExecute a command as another user (typically root)Run as root
sudo commandRun as specific user
sudo -u www-data commandOpen root shell
sudo -ivisudoSafely edit the sudoers fileEdit sudoers safely
sudo visudoEdit a sudoers drop-in file
sudo visudo -f /etc/sudoers.d/customaptDebian/Ubuntu package managerUpdate all packages
sudo apt update && sudo apt upgradeInstall a package
sudo apt install nginxSearch for packages
apt search keywordyumRHEL/CentOS package manager (legacy)Install a package
sudo yum install httpdList installed packages
yum list installeddnfFedora/RHEL 8+ package managerInstall a package
sudo dnf install nginxSearch for packages
dnf search keywordUpgrade all packages
sudo dnf upgrade --refreshpacmanArch Linux package managerFull system upgrade
sudo pacman -SyuInstall a package
sudo pacman -S packageSearch for packages
pacman -Ss keywordapkAlpine Linux package managerInstall a package
apk add nginxUpdate all packages
apk update && apk upgradesnapSnap package managerInstall a snap
sudo snap install code --classicList installed snaps
snap listflatpakFlatpak application managerInstall from Flathub
flatpak install flathub org.gimp.GIMPList installed apps
flatpak listdpkgLow-level Debian package managerInstall a .deb file
sudo dpkg -i package.debCheck if package is installed
dpkg -l | grep nginxrpmLow-level RPM package managerInstall an RPM
sudo rpm -ivh package.rpmQuery installed packages
rpm -qa | grep httpdmountMount a filesystemMount a device
mount /dev/sdb1 /mnt/usbMount an ISO file
mount -o loop image.iso /mnt/isoList all mounts formatted
mount | column -tumountUnmount a filesystemUnmount a device
umount /mnt/usbLazy unmount (when busy)
umount -l /mnt/busyfdiskPartition table manipulatorList all partitions
sudo fdisk -lPartition a disk interactively
sudo fdisk /dev/sdbmkfsBuild a Linux filesystemCreate ext4 filesystem
sudo mkfs.ext4 /dev/sdb1Create XFS filesystem
sudo mkfs.xfs /dev/sdb1lsblkList information about block devicesShow block devices tree
lsblkShow filesystems and UUIDs
lsblk -fblkidLocate/print block device attributesShow all device UUIDs
blkidShow UUID for a device
blkid /dev/sda1ddConvert and copy a file (low-level)Create disk image
dd if=/dev/sda of=backup.img bs=4M status=progressWrite ISO to USB
dd if=ubuntu.iso of=/dev/sdb bs=4M status=progressrsyncFast, versatile file copying toolSync 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 SSHCopy file to remote
scp file.txt user@host:/path/Copy directory from remote
scp -r user@host:/remote/dir/ ./local/tarArchive utilityCreate gzipped archive
tar -czvf archive.tar.gz /path/to/dirExtract gzipped archive
tar -xzvf archive.tar.gzList archive contents
tar -tf archive.tar.gzgzipCompress files with gzipCompress a file
gzip file.txtCompress, keep original
gzip -k file.txtMaximum compression
gzip -9 file.txtgunzipDecompress gzip filesDecompress a file
gunzip file.txt.gzbzip2Compress files with bzip2Compress a file
bzip2 file.txtDecompress, keep original
bzip2 -dk file.txt.bz2xzCompress files with xz (high ratio)Compress a file
xz file.txtDecompress, keep original
xz -dk file.txt.xzzipPackage and compress filesCreate a zip archive
zip archive.zip file1.txt file2.txtZip a directory
zip -r archive.zip directory/unzipExtract zip archivesExtract zip archive
unzip archive.zipExtract to specific directory
unzip archive.zip -d /target/dir/List archive contents
unzip -l archive.zip7z7-Zip file archiver (high compression)Create 7z archive
7z a archive.7z files/Extract 7z archive
7z x archive.7zsshSecure shell remote loginConnect to remote host
ssh user@hostnameConnect on custom port
ssh -p 2222 user@hostnameLocal port forwarding
ssh -L 8080:localhost:80 user@hostscpSecure copy files over SSHUpload a file
scp file.txt user@host:/path/Download a file
scp user@host:/remote/file.txt ./rsyncRemote file synchronization over SSHSync to remote
rsync -avz -e ssh local/ user@host:/remote/Sync from remote
rsync -avz user@host:/remote/ ./local/sftpSecure FTP over SSHStart SFTP session
sftp user@hostnameSFTP on custom port
sftp -P 2222 user@hostnamessh-keygenGenerate SSH key pairsGenerate Ed25519 key
ssh-keygen -t ed25519 -C '[email protected]'Generate 4096-bit RSA key
ssh-keygen -t rsa -b 4096ssh-copy-idCopy SSH public key to a remote hostInstall key on remote
ssh-copy-id user@hostnameSpecify key file
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@hostssh-agentSSH authentication agentStart the SSH agent
eval $(ssh-agent -s)Add key to agent
ssh-add ~/.ssh/id_ed25519systemctlControl systemd services and unitsCheck service status
systemctl status nginxStart a service
systemctl start nginxEnable and start service
systemctl enable --now nginxjournalctlQuery the systemd journalRecent logs for a service
journalctl -u nginx --since '1 hour ago'Follow logs in real time
journalctl -fErrors since last boot
journalctl -p err -btimedatectlControl system time and dateShow current time settings
timedatectlSet timezone
timedatectl set-timezone America/New_YorkhostnamectlControl the system hostnameShow hostname info
hostnamectlSet hostname
hostnamectl set-hostname webserverloginctlControl the systemd login managerList active sessions
loginctl list-sessionsShow user session info
loginctl show-user usernamedocker runCreate and start a containerRun nginx in background
docker run -d -p 80:80 nginxInteractive disposable container
docker run -it --rm ubuntu bashWith volume and env var
docker run -v /host:/container -e VAR=val imagedocker psList running containersShow running containers
docker psShow all containers
docker ps -aCustom format output
docker ps --format 'table {{.Names}}\t{{.Status}}'docker buildBuild an image from a DockerfileBuild 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 containerOpen shell in container
docker exec -it container_name bashRun a command
docker exec container_name ls /appdocker logsFetch logs from a containerView container logs
docker logs container_nameFollow last 100 lines
docker logs -f --tail 100 container_namedocker-composeDefine and run multi-container applicationsStart services in background
docker-compose up -dStop and remove volumes
docker-compose down -vFollow service logs
docker-compose logs -f service_name