Skip to main content

108 entries · 9 sections

Linux Commands Cheat Sheet

The Linux and macOS terminal commands that come up every day — moving around, finding files, reading logs, fixing permissions, killing processes, checking the network and unpacking archives. Ordered by what you are trying to do rather than alphabetically.

Moving around and listing

SyntaxWhat it does
pwdPrint the directory you are currently in.
ls -lhLong listing with human-readable file sizes.
ls -laLong listing including dotfiles.
ls -ltSort by modification time, newest first. Add -r to reverse it.
cd -Return to the previous directory.
cd ~Go to your home directory.
tree -L 2Draw the directory tree two levels deep.
du -sh *Size of each item in the current directory.
du -h --max-depth=1 | sort -hFind which subdirectory is eating the disk. On macOS and BSD the flag is du -d 1 -h.
df -hFree space per mounted filesystem.

Files and directories

SyntaxWhat it does
touch fileCreate an empty file, or update an existing file's timestamp.
mkdir -p a/b/cCreate a directory and any missing parents.
cp file copyCopy a file.
cp -r dir/ dest/Copy a directory and everything inside it.
cp -a src/ dest/Archive copy: recursive and preserving permissions, timestamps and links.
mv old newMove or rename. Same command for both.
rm fileDelete a file.
rm -rf dir/Delete a directory and its contents without prompting. There is no undo.
ln -s /target linkCreate a symbolic link.
stat fileSize, permissions, inode and the access, modify and change times.
file archive.binGuess a file's real type from its contents rather than its extension.
readlink -f pathResolve a path to its absolute, symlink-free form.

Reading and slicing files

SyntaxWhat it does
cat filePrint a whole file.
less filePage through a file. / searches, n repeats, q quits.
head -n 20 fileThe first 20 lines.
tail -n 50 fileThe last 50 lines.
tail -f app.logFollow a log as it is written.
tail -F app.logFollow, and reopen the file if it is rotated out from under you.
wc -l fileCount lines. -w counts words, -c counts bytes.
sort file | uniq -c | sort -rnCount duplicate lines, most frequent first. uniq only collapses adjacent lines, hence the first sort.
cut -d, -f2 data.csvTake the second comma-separated field of every line.
awk '{print $1, $3}' filePrint selected whitespace-separated columns.
sed -i 's/old/new/g' fileReplace text in place. On macOS the flag needs an argument: sed -i '' ...
diff -u a.txt b.txtUnified diff between two files.

Searching

SyntaxWhat it does
grep "text" filePrint the lines that contain the text.
grep -r "text" .Search a whole directory tree.
grep -i "text" fileCase-insensitive.
grep -n "text" fileShow line numbers with each match.
grep -v "text" fileInvert: print the lines that do not match.
grep -E "a|b" fileUse extended regular expressions. -P switches to PCRE where available.
grep -c "text" fileCount matching lines instead of printing them.
grep -rl "text" .List only the names of the files that contain a match.
grep -A3 -B3 "text" fileShow three lines of context after and before each match.
find . -name "*.log"Find files by name pattern. Quote the pattern so the shell does not expand it.
find . -type f -mtime -1Files modified in the last 24 hours.
find . -size +100MFiles larger than 100 MB.
find . -name "*.tmp" -deleteFind and delete in one pass. Run it without -delete first.
command -v nodeWhere a command resolves from, and whether it exists at all.

Permissions and ownership

SyntaxWhat it does
chmod +x script.shMake a file executable.
chmod 644 fileOwner reads and writes, everyone else reads. The normal setting for a file.
chmod 755 dirOwner full, everyone else read and execute. The normal setting for a directory.
chmod 600 ~/.ssh/id_ed25519Owner only. Private keys and secrets need this or SSH refuses them.
chmod -R 755 dir/Apply recursively through a tree.
chown user:group fileChange the owning user and group.
chown -R user: dir/Change ownership through a whole tree.
umask 022The default permission mask applied to newly created files.
sudo commandRun a single command as root.
sudo -u www-data commandRun a command as another user.
idYour user id, group id and every group you belong to.
groups userList the groups a user belongs to.

Processes and jobs

SyntaxWhat it does
ps auxEvery process with its user, CPU and memory use.
ps aux | grep nodeFind a process by name.
topLive process monitor. htop is the friendlier version if it is installed.
kill <pid>Ask a process to shut down cleanly (SIGTERM).
kill -9 <pid>Force-kill (SIGKILL). Last resort — no cleanup handler runs.
pkill -f "node server"Kill by matching the full command line.
pgrep -af nodeList the pids and command lines that match a name.
jobsList the background jobs of this shell.
fg %1 / bg %1Bring job 1 to the foreground / resume it in the background.
nohup cmd &Run a command that survives the terminal closing.
lsof -i :3000Which process is holding port 3000.
time cmdMeasure how long a command takes.

Networking

SyntaxWhat it does
curl -I https://example.comFetch just the response headers.
curl -L -o out.zip <url>Download to a file, following redirects.
curl -s <url> | headFetch quietly and inspect the start of the body.
wget <url>Download a file. -c resumes an interrupted download.
ping -c 4 example.comSend four packets and report the round-trip times.
dig example.com +shortResolve a hostname, output trimmed to the answer.
ss -tulpnListening TCP and UDP sockets with the processes behind them. Replaces netstat.
ip aNetwork interfaces and their addresses.
ip rThe routing table.
traceroute example.comShow the hops between you and a host.
nc -zv host 22Test whether a TCP port is reachable.

Archives and transfers

SyntaxWhat it does
tar -czf a.tar.gz dir/Create a gzip-compressed tarball.
tar -xzf a.tar.gzExtract a gzip tarball.
tar -tzf a.tar.gzList the contents without extracting anything.
tar -xzf a.tar.gz -C /destExtract into a specific directory.
tar -cJf a.tar.xz dir/Create an xz tarball — slower, noticeably smaller.
zip -r a.zip dir/Create a zip archive.
unzip a.zip -d dest/Extract a zip into a directory.
gzip file / gunzip file.gzCompress or decompress a single file in place.
rsync -avz src/ dest/Copy only what changed, preserving permissions and timestamps.
rsync -avz --delete src/ user@host:/dest/Mirror a directory to a remote host, deleting what is no longer in the source.
scp file user@host:/pathCopy a file over SSH.

System, services and packages

SyntaxWhat it does
uname -aKernel version and machine architecture.
cat /etc/os-releaseDistribution name and version.
free -hMemory and swap use.
uptimeHow long the machine has been up, plus the load averages.
systemctl status nginxWhether a service is running, with its recent log lines.
systemctl restart nginxRestart a service. start, stop and reload work the same way.
systemctl enable --now nginxStart a service and make it start at boot.
journalctl -u nginx -fFollow one service's logs.
journalctl -p err -bErrors only, from the current boot.
sudo apt update && sudo apt install pkgDebian and Ubuntu: refresh the index, then install.
sudo dnf install pkgFedora, RHEL and derivatives.
sudo pacman -S pkgArch and derivatives.
apk add pkgAlpine, which is what most slim container images use.
history | grep sshSearch your own command history.

Worth knowing

  • Almost every difference you hit between a Linux server and a Mac terminal is GNU versus BSD tooling. sed -i needs an empty argument on macOS, du uses -d instead of --max-depth, and readlink -f does not exist until you install coreutils. Install coreutils with Homebrew and the g-prefixed commands (gsed, gdu) behave like the server's.
  • Test destructive find and rsync commands before running them. find without -delete just prints what it matched, and rsync --dry-run shows exactly what it would transfer or remove. Both take two seconds and have saved entire directories.
  • Ctrl+R searches your shell history backwards as you type, Ctrl+A and Ctrl+E jump to the start and end of the line, and Ctrl+W deletes the previous word. These readline bindings work in bash, zsh, psql and most REPLs.

Try a snippet instead of reading about it

Reference is faster when you can run the thing. Paste a snippet into AltF Code, the free in-browser editor — real syntax highlighting for HTML, CSS, JavaScript, Python, SQL, JSON and more, with HTML, CSS and JavaScript running live in the preview. No install and no sign-up.

Open the editor

Linux Commands — common questions

What is the difference between chmod 644 and chmod 755?
The three digits are owner, group and others, and each is read (4) plus write (2) plus execute (1). 644 means the owner can read and write while everyone else can only read — right for ordinary files. 755 adds execute for everyone, which directories need in order to be entered and scripts need in order to run.
How do I find which process is using a port?
Run sudo lsof -i :3000 to see the process holding that port, or sudo ss -tulpn | grep 3000 for the same information from the socket table. Once you have the pid, kill <pid> asks it to stop and kill -9 <pid> forces it.
How do I find large files that are filling the disk?
Start with df -h to see which filesystem is full, then du -h --max-depth=1 /var | sort -h to walk down into the biggest directory one level at a time. For a direct hunt, find / -type f -size +500M 2>/dev/null lists every very large file.
What is the difference between grep, find and locate?
grep searches inside file contents, find searches the filesystem by name, size, time and type and can act on what it finds, and locate answers name queries instantly from a prebuilt database — which means it can be out of date until updatedb runs.