Skip to content

Overview

Linux cheat sheet

My own quick reference, built up week by week over the 26-week plan. One line per command, with only the options I actually use. The details and the stories behind them are in the weekly notes.

How to add to it: after each week, move the commands I keep looking up into the right section. Short entries; link to the notes for the long explanation.

Contents

Getting help

Command What it does
type cmd Show what kind of command cmd is: program, builtin, function or alias.
which cmd Show which executable runs for cmd.
help cmd Help for a shell builtin (help cd).
man cmd Manual page. /word searches, n next match, q quits.
apropos word Search manual page descriptions for word.
whatis cmd One-line description of cmd.
info cmd Info entry, sometimes longer than the man page.
alias name='cmd' Define a shortcut; alias alone lists them.

The four kinds of commands are explained in Week 1 notes: Working with Commands.

Command What it does
pwd Print the working directory.
cd dir Change to dir.
cd or cd ~ Go to my home directory.
cd ~user Go to the home directory of user.
cd .. Go up one level.
cd - Go back to the previous directory.
clear Clear the screen (or Ctrl+L).

Listing and inspecting files

Command What it does
ls -l Long listing: type, permissions, links, owner, group, size, date, name.
ls -lh Same, with human-readable sizes.
ls -a Include hidden files (names starting with .).
ls -A Same, without . and ...
ls -lt Sort by modification time, newest first.
ls -S Sort by size, largest first.
ls -d */ Only directories.
ls -R Recursive.
ls -F Mark directories with / and executables with *.
ls -li Show inode numbers (see Links).
file name Show the file type, based on the contents.
tree -L 2 Directory tree, two levels deep (sudo apt install tree).
tree -d Directories only.
tree -a -I node_modules Include hidden files, but skip a pattern.

The fields of ls -l are explained in Week 1 notes: Explanation of ls -l output.

Wildcards

The shell expands these before the command runs.

Pattern Matches
* Any characters, including none.
? Exactly one character.
[abc] One character from the set.
[!abc] One character not in the set.
[a-z] One character in the range.
[[:digit:]], [[:upper:]], [[:alpha:]] POSIX character classes.

Files and directories

Command What it does
mkdir dir1 dir2 Create directories.
mkdir -p a/b/c Create nested directories, including missing parents.
cp -i src dst Copy, asking before overwriting.
cp -r dir1 dir2 Copy a directory and its contents.
cp -a src dst Copy and keep ownership, permissions and timestamps.
cp -u *.html dir Copy only files that are new or newer.
mv old new Rename, or move into a directory.
mv -i src dst Move, asking before replacing.
rm -i file Delete, asking first.
rm -r dir Delete a directory and everything in it.

Warning: there is no recycle bin. Check a wildcard with ls before using it with rm.

Command What it does
ln target name Hard link: a second name for the same inode (same data).
ln -s target name Symbolic link: a small file that points to target by path.
ls -li Hard links share an inode number; the link count is the second column.
readlink -f name Show where a symbolic link finally points.

Finding files

Shape: find <where> <tests> <action>. Tests come first, the action last; with no action, find prints the matches.

Command What it does
find . -type f All regular files below the current directory (-type d directories, -type l symlinks).
find . -name '*.md' Match by name; quote the pattern so the shell doesn't expand it. -iname ignores case.
find . -maxdepth 2 Limit the depth (-mindepth 3 skips the top levels). Put it before the other tests.
find . -size +10M Larger than 10 MB (-size -100c smaller than 100 bytes; 1033c exactly 1033 bytes).
find . -mtime -1 Modified less than 24 h ago (+7 is more than 7 days; whole days, rounded down).
find . -mmin -30 Modified in the last 30 minutes.
find . -user "$USER" Owned by a user (-not -user x for everyone else).
find . -perm -u+x Executable by the owner. -perm 600 exact, -perm -600 all these bits, -perm /600 any of them.
find . ! -executable ! (or -not) negates the next test.
find . \( -name '*.cs' -o -name '*.csproj' \) OR needs -o and escaped parentheses.
find . -empty Empty files; add -type d for empty directories.
find . -xtype l Broken (dangling) symlinks.
find . -name bin -prune -o -name '*.cs' -print Skip a directory. Keep the -print, or the pruned directory prints too.
find . -name '*.log' -exec rm {} + {} + passes many files per run (fast); {} \; runs the command once per file.
find . -name '*.tmp' -delete Run without -delete first, and keep -delete last.
find . -print0 \| xargs -0 cmd Safe with spaces and newlines in names.
find / -name '*.conf' 2>/dev/null Hide "Permission denied"; the redirect belongs to find, so it goes at the end of the command, not after a pipe.
find . -type f -printf '%s %p\n' \| sort -rn \| head The 10 largest files (size in bytes, then path).
locate name Instant, but reads a daily index (sudo updatedb to refresh).
fd pattern Friendly and fast, skips hidden and ignored files (fdfind on Ubuntu).

What I'd forget:

  • -mtime +7 does not match 7.5 days old; use -mmin for exact limits.
  • -exec ... \; needs the escaped semicolon; + does not.
  • -name matches only the file name, never a path (-path does that).
  • Put -maxdepth before other tests or find prints a warning.

Tricky file names

Situation What works
File named - cat ./- or cat < - (plain cat - reads standard input).
Name with spaces Quote it: cat 'my file.txt'.
Name starting with - cat ./-name or cat -- -name.
Hidden file Starts with .; see it with ls -a.

Viewing files

Command What it does
cat file Print the whole file.
less file Page through a file. Space next page, b back, /word search, q quit.
head -n 3 file First 3 lines (default 10).
tail -n 3 file Last 3 lines (default 10). tail -n +5 file prints from line 5 onwards.
tail -f file Follow a file live (it keeps the open file, so it misses a rotated or replaced file). Ctrl-C stops tail only.
tail -F file Follow by name and retry: survives rotation, deletion and a file that does not exist yet. Use it for logs.
tail -n 0 -f file Follow only new lines, no history.
less +F file Like tail -f, but Ctrl-C drops into normal less (scroll, search); F resumes following, q quits.
tail -f f \| grep --line-buffered X Filter a live stream; --line-buffered is needed when another command follows in the pipe.

Disk usage

Command What it does
df -h Free and used space per mounted filesystem, human-readable. df -hT adds the filesystem type (Windows drives show as 9p or drvfs in WSL).
du -sh dir One total for a directory (-s summary, -h human-readable).
du -h --max-depth=1 \| sort -h Size of each immediate subdirectory, smallest to largest.
du -ah \| sort -rh \| head The 10 biggest files and directories under here.
du -x Stay on one filesystem (skips /mnt/c in WSL).
ls -l /proc/<pid>/fd Files a process holds open. Fds 0, 1, 2 are stdin, stdout, stderr.
ls -l /proc/*/fd 2>/dev/null \| grep deleted Deleted files still held open: they keep using disk space until the process closes them.
: > file Truncate a file in place. Safe for a log a running process writes to; deleting it is not.

df asks the filesystem how full the disk is; du adds up the files under a tree. They can disagree: a deleted file that a running process still holds open counts in df but is invisible to du.

Pipes and text tools

Command What it does
cmd \| tr -d ' \n' Delete all spaces and newlines from the output.
cmd > file Send stdout to a file (overwrites). >> appends, which keeps tail -f working.
cmd > file 2>&1 Send stdout and stderr to the same file. Order matters: 2>&1 > file leaves stderr on the screen.
cmd 2>&1 \| tee file Show the output on screen and save it to a file.

Week 3: add grep, sort, uniq, cut, sed, awk.

Editors, tmux and SSH

Command What it does
ssh -p 2220 user@host Connect over SSH on a non-default port.

Week 4: add vim, tmux and SSH key basics.

Users, groups and permissions

Command What it does
sudo chown -R $USER:$USER dir Make me the owner of dir and everything in it.

Week 5: add chmod, id, groups and sudo.

Processes and signals

Week 6.

systemd and journald

Week 7.

Packages and storage

Week 8.

Networking

Week 13.

Firewalls

Week 14.

Bash scripting

Weeks 15-16.

Docker

Weeks 17-20.

Ansible

Weeks 23-24.

WSL and git

Command What it does
cd ~/src Keep repos in the Linux filesystem; /mnt/c is much slower.
time cmd Measure how long cmd takes.
code . Open the current folder in VS Code (WSL extension).
gh auth setup-git Let git use the GitHub CLI token for HTTPS remotes.
ssh-keygen -t ed25519 Create an SSH key; add the .pub file at github.com/settings/keys.
git config core.hooksPath .githooks Enable this repo's pre-push markdownlint hook.