Table of Contents
Here are 20 commonly used Unix commands and their typical usage examples. This post is for my personal reference.
Search
grep
Prints the lines that match a pattern, from files or piped input.
grep -rn "TODO" src/ # search recursively, with line numbers
grep -i "error" app.log # ignore case
grep -v "DEBUG" app.log # show lines that do NOT match
grep -E "ERROR|WARN" app.log # match either pattern (extended regex)
grep -c "404" app.log # count matching lines
rg
ripgrep is a faster grep that searches subfolders by default and skips files listed in .gitignore.
rg "TODO" . # search the current folder recursively
rg -t py "def main" . # only Python files
rg -l "panic" . # only the names of matching files
rg -C 3 "panic" . # 3 lines of context around each match
rg -g '!src/*' "ERROR" . # exclude a path with a glob
View and write text
cat
Prints or joins files. With a heredoc (<< EOF), it also writes multi-line text from a script.
cat file.txt # print a file
cat a.txt b.txt > all.txt # join files into one
cat > config.yml << 'EOF' # create a file; quoted 'EOF' keeps $VARS literal
path: $HOME
EOF
cat >> notes.txt << EOF # append; unquoted EOF expands variables
Built on $(date +%F)
EOF
cat << 'EOF' | python # pipe an inline script into a program
print("hello")
EOF
head
Shows the start of a file or of a command’s output.
head file.txt # first 10 lines
head -n 50 file.txt # first 50 lines
head -c 200 file.bin # first 200 bytes
head -n -5 file.txt # everything except the last 5 lines (GNU)
ls -t | head -n 5 # the 5 most recently modified files
tail
Shows the end of a file or of a command’s output, or follows a file as it grows.
tail file.txt # last 10 lines
tail -n 100 app.log # last 100 lines
tail -f app.log # follow new lines live
tail -n +2 data.csv # everything from line 2, which skips a CSV header
tail -F app.log # keep following across log rotation
wc
Counts lines, words or bytes.
wc -l file.txt # count lines
wc -w essay.txt # count words
wc -c file.bin # count bytes
wc -l src/* # per-file counts plus a total
git ls-files | wc -l # count the lines of any command's output
Transform
sed
Edits a stream of text line by line, mostly for find-and-replace and printing line ranges.
sed 's/old/new/g' file.txt # replace all matches, print the result
sed -i 's/old/new/g' file.txt # edit in place (macOS: sed -i '')
sed -n '70,110p' file.py # print only lines 70-110
sed '/^#/d; /^$/d' config.ini # delete comments and blank lines
sed -E 's/(.+)@(.+)/\2: \1/' f # reorder text with regex groups
jq
Filters, reshapes and edits JSON.
jq . data.json # pretty-print
jq -r '.version' package.json # one field, without quotes
jq '.items[] | select(.active) | .name' d.json # filter an array
jq '.items | length' d.json # count items
jq '.version = "2.0.0"' package.json > tmp && mv tmp package.json # change a value
awk
Processes text as rows and columns, for picking fields, filtering rows and adding things up.
awk '{print $1}' access.log # first column (split on whitespace)
awk -F, '{print $2}' data.csv # second column, split on commas
awk '$2 > 100' data.txt # rows where column 2 is over 100
awk '{sum += $2} END {print sum}' data.txt # total of column 2
awk '!seen[$0]++' file.txt # remove duplicates, keeping the order
sort
Sorts lines alphabetically, numerically or by a chosen column.
sort names.txt # alphabetical
sort -n numbers.txt # numeric, so 9 comes before 10
sort -rn numbers.txt # numeric, largest first
sort -t, -k2,2n data.csv # by the second comma-separated column, as numbers
sort -h sizes.txt # human-readable sizes, such as 1K, 3M, 2G
uniq
Removes or counts repeated lines. It only compares neighbouring lines, so sort first.
sort names.txt | uniq # remove duplicates
sort names.txt | uniq -c # count each line
sort names.txt | uniq -c | sort -rn # most frequent first
sort names.txt | uniq -d # only lines that repeat
sort names.txt | uniq -u # only lines that never repeat
tr
Replaces, squeezes or deletes individual characters. It reads standard input only, so use < or a pipe.
tr 'a-z' 'A-Z' < file.txt # convert to uppercase
tr -d '\r' < windows.txt > unix.txt # remove Windows line endings
tr -s ' ' < file.txt # squeeze repeated spaces into one
echo 'a,b,c' | tr ',' '\n' # put each item on its own line
echo 'tel: 555-1234' | tr -cd '0-9' # keep only the digits
cut
Extracts columns or character ranges from each line.
cut -d, -f1 data.csv # first comma-separated column
cut -d, -f1,3 data.csv # columns 1 and 3
cut -d, -f2- data.csv # column 2 onwards
cut -f2 data.tsv # second column; the default separator is a tab
cut -c1-80 file.txt # first 80 characters of each line
Batch operations
find
Locates files by name, type, age or size, and can act on them.
find . -name "*.log" # by name
find . -type f -size +50M # files over 50 MB
find . -type f -mtime -1 # changed in the last 24 hours
find . -name "*.ts" -not -path "*/node_modules/*" # exclude a folder
find . -name "*.tmp" -delete # delete matches; run it without -delete first
xargs
Turns input lines into arguments for another command.
find . -name "*.md" -print0 | xargs -0 grep -l "draft" # safe with spaces in names
cat urls.txt | xargs -n 1 curl -sO # one command per line of input
cat files.txt | xargs -I{} cp {} backup/ # put the argument anywhere
cat urls.txt | xargs -P 4 -n 1 curl -sO # 4 jobs in parallel
find . -name "*.tmp" -print0 | xargs -0 -t rm # print each command as it runs
Git and GitHub
git
Tracks changes, branches and history in a repository.
git status -sb # short status with the branch
git log --oneline --graph -20 # compact recent history
git diff --stat main...HEAD # what this branch changes
git switch -c feature/login # create a branch and switch to it
git stash push -m "wip" # set aside uncommitted work
gh
GitHub’s CLI works with pull requests, issues, CI runs and the API from the terminal.
gh pr create --fill # open a PR from your commits
gh pr checkout 123 # check out a PR locally
gh issue list --assignee @me # your assigned issues
gh run watch # follow a CI run live
gh api repos/cli/cli --jq .stargazers_count # call the API directly
Network
curl
Sends network requests, for calling APIs, downloading files and checking endpoints.
curl -s https://api.github.com/repos/cli/cli | jq .name # GET and parse the JSON
curl -fsSL -o file.zip https://example.com/file.zip # download; follow redirects, fail on HTTP errors
curl -I https://example.com # headers only
curl -X POST -H "Content-Type: application/json" -d '{"a":1}' https://httpbin.org/post
curl -s -o /dev/null -w "%{http_code} %{time_total}s\n" https://example.com # status and timing
Processes
timeout
Stops a command that runs too long. It doesn’t put anything in the background by itself; & does that, and the two work well together.
timeout 30s make test; echo $? # exit code 124 means it timed out
timeout -k 5s 60s ./server.sh # TERM at 60s, KILL 5s later if still running
timeout -s INT 10s ./capture.sh # send an interrupt so it can clean up
nohup timeout 1h ./job.sh > job.log 2>&1 & # background job, capped at 1 hour
timeout 60s bash -c 'until curl -sf localhost:4321; do sleep 1; done' # wait for a server
ps
Lists running processes and their resource use. These examples need the Linux version from procps; Git Bash and BusyBox reject most of these flags.
ps aux --sort=-%mem | head # top memory users
ps aux --sort=-%cpu | head # top CPU users
ps -ef | grep '[n]ode' # find a process; [n] stops grep matching itself
ps -p 1234 -o pid,ppid,etime,cmd # details for one PID
ps -ef --forest # parent/child tree
Putting them together
The commands get more useful in a pipeline. These all ran against this blog’s repository:
# Which files change most often?
git log --name-only --format= | sort | uniq -c | sort -rn | head -5
# How many AsciiDoc posts are there?
git ls-files 'src/content/posts/*.adoc' | wc -l
# What are the first few dependencies?
jq -r '.dependencies | keys[]' package.json | head -5
The first one prints WRITING.md at the top with 14 changes, which is about right for a guide I keep in step with the site.
What I left out
This isn’t a complete list. Each command here also has far more options than five examples can show, so man grep or rg --help is the next stop.
The flags aren’t the same everywhere, either. I tested GNU versions, and macOS ships BSD versions of several of these, so sed -i and head -n -5 in particular need checking there.
About the Author
Wei Li is a passionate software professional who builds enterprise applications with modern technologies. The guides here come from that work: each one explains a feature and shows it in working code. Read more on the About page, or find Wei Li on GitHub. |