Linux Command Cheat Sheet
Ten groups from files to networking, plus process signals
126 commands
ls -lahFilesList files with hidden entries and human-readable sizes.
ls -lah /var/log
cd /pathFilesChange directory; cd - returns to the previous one.
cd /etc/nginx && cd -
pwdFilesPrint the current working directory.
pwd
cp -r src dstFilesCopy directories recursively; -a keeps permissions and timestamps.
cp -a /etc/nginx /backup/nginx
mv src dstFilesMove or rename files and directories.
mv app.log app.log.bak
rm -rf dirFilesRecursive forced delete. Destructive: list the path first.
rm -rf /tmp/build
mkdir -p a/b/cFilesCreate directories recursively, including missing parents.
mkdir -p /data/app/logs
touch fileFilesCreate an empty file or update timestamps.
touch /tmp/health.ok
ln -s target linkFilesCreate a symbolic link, handy for versioned releases.
ln -s /opt/app-1.2.0 /opt/app-current
stat fileFilesShow permissions, size, and timestamps of a file.
stat /etc/nginx/nginx.conf
file targetFilesIdentify the real type of a file from its content.
file /data/export.bin
tree -L 2FilesPrint a directory tree limited to two levels.
tree -L 2 -I node_modules
find /path -name "*.log"FilesFind files by name with wildcard support.
find /var/log -name "*.log" -size +100M
find /path -mtime +7 -deleteFilesDelete files last modified more than seven days ago.
find /tmp -name "*.tmp" -mtime +7 -delete
locate keywordFilesLook up paths from an index, much faster than find.
sudo updatedb && locate nginx.conf
cat fileTextPrint a whole file; fine for small ones.
cat /etc/os-release
less fileTextPage through large files; slash searches, q quits.
less /var/log/nginx/access.log
head -n 20 fileTextShow the first lines of a file.
head -n 20 access.log
tail -n 50 -f fileTextFollow the end of a file in real time.
tail -f /var/log/nginx/error.log
grep -rn "keyword" dirTextSearch recursively and show line numbers.
grep -rn --include="*.ts" "TODO" src/
grep -v "pattern" fileTextInvert the match and print non-matching lines.
grep -v "^#" nginx.conf
sed -i "s/old/new/g" fileTextReplace in place; -i edits the file directly.
sed -i "s/8080/8081/g" config.yml
sed -n "10,20p" fileTextPrint only a range of lines.
sed -n "10,20p" app.log
awk "{print $1, $3}" fileTextExtract fields by column; $0 is the whole line.
awk "{print $1}" access.log | sort | uniq -ccut -d: -f1 fileTextCut columns by delimiter, good for fixed formats.
cut -d: -f1 /etc/passwd
sort -u fileTextSort and dedupe; -n numeric, -r reverse.
sort -nr access.log | head
uniq -cTextCount adjacent duplicates; sort first.
sort access.log | uniq -c | sort -nr
wc -l fileTextCount lines; -c counts bytes.
wc -l access.log
dos2unix fileTextConvert Windows CRLF line endings to Unix LF.
dos2unix win.txt
tr -s " "TextSqueeze repeated characters, handy for extra spaces.
tr -s " " < in.txt > out.txt
xargs -I{} cmd {}TextBuild command arguments from standard input.
find . -name "*.tmp" | xargs rm -f
tee fileTextWrite to both stdout and a file.
echo "1.2.3" | sudo tee /etc/app/version
diff -u a bTextCompare two files in unified format.
diff -u old.conf new.conf
chmod 755 filePermissionsSet permissions: owner rwx, others read and execute.
chmod -R 755 /var/www/html
chmod -R 644 dirPermissionsMake files readable by all and writable by owner only.
chmod -R 644 /etc/app/*.conf
chown -R user:group dirPermissionsChange owner and group recursively.
chown -R www-data:www-data /var/www
chgrp group filePermissionsChange only the group.
chgrp developers /srv/project
umask 022PermissionsSet the default permission mask for new files.
umask 022
useradd -m -s /bin/bash adaPermissionsCreate a user with a home directory and login shell.
useradd -m -s /bin/bash ada
usermod -aG docker adaPermissionsAppend a user to a supplementary group; without -a the others are replaced.
usermod -aG docker ada
passwd userPermissionsChange the password of a user.
sudo passwd ada
su - userPermissionsSwitch user and load that environment.
su - postgres
sudo -iPermissionsStart a login shell as root.
sudo -i
idPermissionsShow the current uid, gid, and groups.
id
groups userPermissionsList all groups a user belongs to.
groups www-data
ps auxProcessesSnapshot all processes; filter with grep.
ps aux | grep -v grep | grep nginx
topProcessesLive CPU and memory view; M sorts by memory.
top -b -n 1 | head -20
htopProcessesFriendlier interactive process viewer; install separately.
htop
kill <pid>ProcessesSend SIGTERM to ask a process to exit gracefully.
kill 12345
kill -9 <pid>ProcessesForce kill; may lose data, use only when SIGTERM fails.
kill -9 12345
pkill -f "java -jar"ProcessesKill processes matching the full command line.
pkill -f "java -jar app.jar"
killall nginxProcessesKill all processes with the given name.
killall -HUP nginx
jobs / bg / fgProcessesList background jobs and move them between foreground and background.
jobs -l
nohup cmd &ProcessesKeep a process running after logout, logging to nohup.out.
nohup ./start.sh > app.log 2>&1 &
nice -n 10 cmdProcessesStart with lower priority to avoid starving key services.
nice -n 10 tar -czf backup.tgz /data
renice -n -5 -p <pid>ProcessesAdjust the priority of a running process.
sudo renice -n -5 -p 12345
watch -n 2 cmdProcessesRe-run a command every two seconds.
watch -n 2 "df -h /"
lsof -p <pid>ProcessesList files and sockets opened by a process.
lsof -p 12345 | head
uname -aSystemShow kernel version and architecture.
uname -a
uptimeSystemShow uptime and load averages.
uptime
free -hSystemShow memory and swap usage.
free -h
vmstat 1SystemReport CPU, memory, IO, and context switches every second.
vmstat 1 5
iostat -x 1SystemShow per-disk IO utilization and wait.
iostat -x 1
envSystemPrint all environment variables.
env | grep PATH
export KEY=valueSystemSet an environment variable for the current session only.
export NODE_ENV=production
historySystemShow command history; !! repeats the last command.
history | grep systemctl
alias ll="ls -lah"SystemDefine a command alias.
alias ll="ls -lah"
date -d "@1700000000"SystemFormat a timestamp as a date.
date -d "@1700000000" "+%F %T"
timedatectlSystemShow and set timezone and NTP sync state.
timedatectl set-timezone Asia/Shanghai
ulimit -nSystemShow or set the file descriptor limit.
ulimit -n 65535
sysctl -w net.core.somaxconn=1024SystemTemporarily change a kernel parameter.
sysctl -w net.ipv4.ip_forward=1
crontab -eSystemEdit the crontab of the current user.
crontab -l
ip addrNetworkingShow interfaces and addresses; replaces ifconfig.
ip -br addr
ip routeNetworkingShow the routing table and default gateway.
ip route get 8.8.8.8
ss -tulpnNetworkingList listening ports with owning processes.
ss -tulpn | grep 8080
netstat -anpNetworkingShow all connections; still common on older systems.
netstat -anp | grep ESTABLISHED
ping -c 4 hostNetworkingConnectivity test with four packets.
ping -c 4 8.8.8.8
traceroute hostNetworkingShow the route hop by hop.
traceroute example.com
dig +short example.comNetworkingQuery DNS records, useful for resolution issues.
dig +short example.com A
nslookup example.com 8.8.8.8NetworkingQuery a specific DNS server.
nslookup example.com 8.8.8.8
curl -I https://example.comNetworkingFetch response headers only.
curl -I -L https://example.com
curl -X POST -d "{}" urlNetworkingSend a JSON request body.
curl -X POST -H "Content-Type: application/json" -d "{}" http://localhost:8080/apiwget -c urlNetworkingDownload with resume support.
wget -c https://example.com/big.iso
ssh -i key.pem user@hostNetworkingLog in to a remote host with a key.
ssh -i ~/.ssh/id_ed25519 ada@10.0.0.5
scp -r dir user@host:/pathNetworkingCopy directories recursively between hosts.
scp -r ./dist root@10.0.0.5:/var/www
rsync -avz --delete src/ dst/NetworkingIncremental sync; --delete mirrors the source.
rsync -avz --delete ./dist/ deploy@10.0.0.5:/var/www/
nc -zv host 8080NetworkingCheck whether a remote port is reachable.
nc -zv 10.0.0.5 8080
tcpdump -i any port 8080NetworkingCapture packets on a port; -w writes a file.
tcpdump -i any -nn port 8080 -w dump.pcap
df -hStorageShow disk usage per filesystem.
df -h
du -sh *StorageSummarize sizes of entries in the current directory.
du -sh /* 2>/dev/null | sort -h
lsblkStorageShow block devices and mount points as a tree.
lsblk -f
fdisk -lStorageList disks and partition tables.
sudo fdisk -l
mount /dev/sdb1 /dataStorageMount a device at a directory.
mount -o ro /dev/sdb1 /mnt
umount /dataStorageUnmount; if busy, find the user with lsof first.
umount /data
mkfs.ext4 /dev/sdb1StorageFormat a partition. Destroys existing data.
mkfs.ext4 -L data /dev/sdb1
fsck /dev/sdb1StorageCheck and repair a filesystem; unmount first.
fsck -y /dev/sdb1
tar -czf out.tgz dirStorageCreate a gzipped tar archive.
tar -czf backup-$(date +%F).tgz /data/app
tar -xzf in.tgz -C dirStorageExtract an archive into a directory.
tar -xzf app.tgz -C /opt
zip -r out.zip dirStorageCreate a zip archive recursively.
zip -r site.zip ./dist
xz -9 fileStorageCompress with a high ratio at the cost of speed.
xz -9 -T0 big.sql
systemctl start <unit>ServicesStart a service; enable makes it start on boot.
systemctl enable --now nginx
systemctl status <unit>ServicesShow service status and recent logs.
systemctl status nginx
systemctl list-units --failedServicesList units that failed to start.
systemctl list-units --failed
journalctl -u <unit>ServicesShow logs of a unit.
journalctl -u nginx --since "1 hour ago"
journalctl -fServicesFollow the system journal.
journalctl -f -p err
dmesg -TServicesRead the kernel ring buffer.
dmesg -T | tail -50
apt update && apt upgradeServicesDebian family index and package upgrade.
sudo apt update && sudo apt upgrade -y
apt install <pkg>ServicesInstall a package.
sudo apt install -y curl
dpkg -l | grep <pkg>ServicesList installed packages and versions.
dpkg -l | grep nginx
dnf install <pkg>ServicesInstall on RHEL family; older releases use yum.
sudo dnf install -y nginx
strace -p <pid>TroubleshootingTrace system calls of a process to find where it hangs.
strace -p 12345 -f -e trace=network
lsof -i :8080TroubleshootingFind the process using a port.
sudo lsof -i :8080
ss -sTroubleshootingSummarize socket counts.
ss -s
iptables -L -n --line-numbersTroubleshootingList firewall rules with line numbers.
iptables -L INPUT -n --line-numbers
ufw allow 8080/tcpTroubleshootingAllow a port with the simplified firewall.
ufw status verbose
nc -l 9000TroubleshootingListen on a local port for connectivity tests.
nc -l 9000
tail -f /var/log/syslogTroubleshootingFollow the system log; the path varies by distribution.
tail -f /var/log/messages
grep -i "error" /var/log/*.logTroubleshootingGrep error lines across logs.
grep -iE "error|fail" /var/log/app/*.log | tail -30
kill -15 <pid>SignalsSIGTERM: request a graceful shutdown, the default.
kill -15 12345
kill -9 <pid>SignalsSIGKILL: the kernel kills it immediately, no cleanup.
kill -9 12345
kill -1 <pid>SignalsSIGHUP: services often reload their configuration.
kill -1 $(cat /run/nginx.pid)
kill -2 <pid>SignalsSIGINT: same as pressing Ctrl+C.
kill -2 12345
kill -3 <pid>SignalsSIGQUIT: the JVM dumps thread stacks and exits.
kill -3 12345
kill -18 / -19 <pid>SignalsSIGCONT and SIGSTOP: resume and pause a process.
kill -19 12345 && kill -18 12345
kill -10 <pid>SignalsSIGUSR1: user-defined, for example reopening logs in Nginx.
kill -10 <nginx master pid>
kill -lSignalsList all signal numbers and names.
kill -l
Something broken or missing?
Send feedback