On this page

Terminal Productivity Cheat Sheet

The terminal is the fastest interface for software engineering — if you know the tools. This cheat sheet covers the commands, configurations, and workflows that eliminate friction. Each tool builds on the last: tmux gives you sessions, zsh gives you a better shell, fzf gives you fuzzy search, ripgrep gives you fast code search, and jq gives you structured JSON processing.

Shell Keyboard Shortcuts (bash & zsh, emacs mode)

These work in any readline/zle shell before you install anything.

KeysAction
Ctrl+A / Ctrl+EStart / end of line
Alt+B / Alt+FBack / forward one word
Ctrl+WDelete word before cursor
Ctrl+U / Ctrl+KDelete to start / end of line (bash: Ctrl+U cuts to start; zsh: whole line)
Ctrl+YPaste what you just deleted
Ctrl+RSearch history backwards (press again for older matches)
Ctrl+LClear screen, keep the current line
Ctrl+X Ctrl+EEdit the current command in $EDITOR (zsh needs edit-command-line bound)
Alt+.Insert last argument of the previous command (repeat to go further back)
Ctrl+_Undo

History Expansion

ExpressionExpands to
!!Previous command (sudo !!)
!$Last argument of previous command
!*All arguments of previous command
!gitMost recent command starting with git
^old^newRe-run previous command with old replaced by new
cd -Back to previous directory

tmux — Terminal Multiplexer

tmux lets you create persistent terminal sessions that survive SSH disconnects, split your screen into panes, and switch between window layouts instantly.

Session Management

CommandDescription
tmux new -s workCreate a new session named "work"
tmux lsList all sessions
tmux attach -t workAttach to session "work"
tmux kill-session -t workKill session "work"
tmux kill-serverKill all sessions
tmux new -A -s workAttach to "work", creating it if it doesn't exist
tmux aAttach to the most recent session
tmux attach -d -t workAttach and detach other clients (fixes a tiny window size)
tmux source-file ~/.tmux.confReload config in a running server

Key Bindings (prefix: Ctrl+b)

KeysAction
Ctrl+b dDetach from session (session keeps running)
Ctrl+b cCreate new window
Ctrl+b n / Ctrl+b pNext / previous window
Ctrl+b 0-9Switch to window by number
Ctrl+b ,Rename current window
Ctrl+b &Close current window
Ctrl+b %Split pane vertically (new pane to the right, side by side)
Ctrl+b "Split pane horizontally (new pane below, stacked)
Ctrl+b arrowMove between panes
Ctrl+b zZoom pane (toggle fullscreen)
Ctrl+b xClose current pane
Ctrl+b [Enter scroll/copy mode (q to exit)
Ctrl+b :Command prompt
Ctrl+b s / Ctrl+b wChoose session / window from a tree
Ctrl+b $Rename session
Ctrl+b ( / Ctrl+b )Previous / next session
Ctrl+b lLast (previously used) window
Ctrl+b SpaceCycle pane layouts
Ctrl+b { / Ctrl+b }Swap pane with previous / next
Ctrl+b !Break pane out into its own window
Ctrl+b Ctrl+arrowResize pane
Ctrl+b qShow pane numbers (press a number to jump)
Ctrl+b ?List all key bindings
# Type into every pane of a window at once (e.g. same command on several servers)
Ctrl+b :setw synchronize-panes on

# Copy mode with vi keys: v to select, y to copy (add to ~/.tmux.conf)
setw -g mode-keys vi
bind -T copy-mode-vi v send -X begin-selection
bind -T copy-mode-vi y send -X copy-selection-and-cancel
# ~/.tmux.conf

# Remap prefix from Ctrl+b to Ctrl+a (easier to reach)
unbind C-b
set -g prefix C-a
bind C-a send-prefix

# Split panes with | and -
bind | split-window -h -c "#{pane_current_path}"
bind - split-window -v -c "#{pane_current_path}"
unbind '"'
unbind %

# New window in current directory
bind c new-window -c "#{pane_current_path}"

# Switch panes with Alt+arrow (no prefix needed)
bind -n M-Left select-pane -L
bind -n M-Right select-pane -R
bind -n M-Up select-pane -U
bind -n M-Down select-pane -D

# Mouse mode (scroll, click panes, resize)
set -g mouse on

# Start numbering at 1 (0 is far from the prefix key)
set -g base-index 1
setw -g pane-base-index 1

# Renumber windows when one is closed
set -g renumber-windows on

# Increase scrollback
set -g history-limit 50000

# Faster key recognition
set -sg escape-time 0

# 256 colors
set -g default-terminal "tmux-256color"

# True colour (24-bit) passthrough for the outer terminal (tmux 3.2+)
set -as terminal-features ",xterm-256color:RGB"

# Copy to the system clipboard via OSC 52 (works over SSH in most terminals)
set -g set-clipboard on

# Status bar
set -g status-style bg=colour235,fg=colour136
set -g status-left '#[fg=green]#S '
set -g status-right '#[fg=yellow]%H:%M'

tmux Scripting — Automated Dev Environment

#!/bin/bash
# ~/bin/dev-session.sh — Launch a full dev environment
# Targets windows by name, so it works whatever base-index is set to.

SESSION="dev"
DIR=~/project

# Re-attach if it already exists
tmux has-session -t "$SESSION" 2>/dev/null && exec tmux attach -t "$SESSION"

tmux new-session -d -s "$SESSION" -n editor -c "$DIR"

# Window 1: Editor
tmux send-keys -t "$SESSION:editor" 'nvim .' C-m

# Window 2: Server
tmux new-window -t "$SESSION" -n server -c "$DIR"
tmux send-keys -t "$SESSION:server" 'npm run dev' C-m

# Window 3: Tests (split into two panes)
tmux new-window -t "$SESSION" -n tests -c "$DIR"
tmux send-keys -t "$SESSION:tests" 'npm run test:watch' C-m
tmux split-window -h -t "$SESSION:tests" -c "$DIR"     # new pane becomes active
tmux send-keys -t "$SESSION:tests" 'npm run lint:watch' C-m

# Window 4: Git / terminal
tmux new-window -t "$SESSION" -n git -c "$DIR"
tmux send-keys -t "$SESSION:git" 'git status' C-m

# Focus on editor
tmux select-window -t "$SESSION:editor"

tmux attach -t "$SESSION"

zsh + oh-my-zsh

Essential Plugins

# ~/.zshrc
plugins=(
  git              # git aliases (gst, gco, gp, etc.)
  z                # Jump to frequent directories
  fzf              # Fuzzy finding integration
  zsh-autosuggestions    # Fish-like suggestions (third-party, install below)
  docker           # Docker completions
  kubectl          # kubectl completions and aliases
  npm              # npm completions
  aws              # AWS CLI completions
  zsh-syntax-highlighting # Command highlighting (third-party; must be LAST)
)

zsh-autosuggestions and zsh-syntax-highlighting are not bundled with oh-my-zsh. Clone them first, or the shell prints "plugin not found":

git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions
git clone https://github.com/zsh-users/zsh-syntax-highlighting ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting

Startup time

Every plugin adds to shell startup. Measure with time zsh -i -c exit (aim for well under 200 ms). Lighter alternatives: a plugin manager such as antidote or zinit, and starship for the prompt.

Must-Know oh-my-zsh Git Aliases

AliasFull Command
gstgit status
gagit add
gaagit add --all
gcgit commit
gc!git commit --verbose --amend
gcogit checkout
gcbgit checkout -b
gsw / gswcgit switch / git switch -c
gpgit push
gpfgit push --force-with-lease --force-if-includes
gpf!git push --force
glgit pull
gloggit log --oneline --decorate --graph
gdgit diff
gdsgit diff --staged
grbgit rebase
gstagit stash push
gstpgit stash pop

Run alias | grep git to see what your oh-my-zsh version actually defines; aliases change between releases.

z — Directory Jumping

z learns your most-used directories and lets you jump to them with partial names.

# After visiting directories normally, z remembers them
cd ~/projects/knowledge-vault
cd ~/projects/api-server
cd /var/log

# Later, jump by partial match
z vault    # → ~/projects/knowledge-vault
z api      # → ~/projects/api-server
z log      # → /var/log

zoxide is a faster, shell-agnostic successor (bash, zsh, fish, PowerShell):

eval "$(zoxide init zsh)"   # in ~/.zshrc (use "bash" in ~/.bashrc)
z vault                     # jump
zi vault                    # pick interactively with fzf

Custom Aliases Worth Adding

# ~/.zshrc

# Quick edit
alias zshrc="$EDITOR ~/.zshrc"
alias reload="source ~/.zshrc"

# Better defaults
alias ls="ls --color=auto"
alias ll="ls -alFh"
alias grep="grep --color=auto"
alias df="df -h"
alias du="du -sh"

# Safety
alias rm="rm -i"
alias cp="cp -i"
alias mv="mv -i"

# Modern replacements
alias cat="bat"        # cat with syntax highlighting (Debian/Ubuntu binary is "batcat")
alias ls="eza"         # ls with git integration (overrides the ls alias above: keep one)
alias find="fd"        # faster, friendlier find
alias top="btop"       # better process viewer

# Docker shortcuts
alias dps="docker ps --format 'table {{.ID}}\t{{.Names}}\t{{.Status}}\t{{.Ports}}'"
alias dlog="docker logs -f"
alias dex="docker exec -it"

# Kubernetes shortcuts
alias k="kubectl"
alias kgp="kubectl get pods"
alias kgs="kubectl get svc"
alias klog="kubectl logs -f"
alias kctx="kubectx"
alias kns="kubens"

# Quick server
alias serve="python3 -m http.server 8080"

# IP addresses
alias myip="curl -s ifconfig.me"
alias localip="hostname -I | awk '{print \$1}'"   # Linux only; macOS: ipconfig getifaddr en0

# Port finder
alias ports="lsof -i -P -n | grep LISTEN"

# JSON pretty print
alias json="jq ."

zsh-autosuggestions Is Life-Changing

This plugin suggests commands as you type based on your history. Press the right arrow key to accept the suggestion. After a week, you will wonder how you ever lived without it.


fzf — Fuzzy Finder

fzf is a general-purpose fuzzy finder that integrates with everything. It transforms interactive selection from "scroll through a list" to "type a few characters and find it instantly."

Installation & Shell Integration

# Install
brew install fzf     # macOS
sudo apt install fzf  # Debian/Ubuntu

# Enable key bindings (add to ~/.zshrc) — fzf 0.48+
source <(fzf --zsh)          # bash: eval "$(fzf --bash)"   fish: fzf --fish | source

# Older fzf: source the files your package installed. Paths vary by distro:
#   Arch:          /usr/share/fzf/key-bindings.zsh, /usr/share/fzf/completion.zsh
#   Debian/Ubuntu: /usr/share/doc/fzf/examples/key-bindings.zsh
source /usr/share/fzf/key-bindings.zsh
source /usr/share/fzf/completion.zsh

Check your version with fzf --version; distro packages (e.g. Ubuntu 24.04 ships 0.44) can be older than --zsh support. Install from GitHub releases or brew for the latest.

Key Bindings

BindingAction
Ctrl+RFuzzy search command history
Ctrl+TFuzzy find files and insert path
Alt+CFuzzy find directories and cd into them
**<Tab>Trigger fzf completion (e.g., cd **<Tab>, kill -9 **<Tab>, ssh **<Tab>)

Inside fzf: Tab / Shift+Tab mark multiple items (with -m), Ctrl+J/Ctrl+K move, and the query understands 'exact, ^prefix, suffix$, !exclude and a | b (OR).

Powerful fzf Recipes

# Preview files while searching
fzf --preview 'bat --color=always --line-range :500 {}'

# Search and open in editor
vim $(fzf --preview 'bat --color=always {}')

# Git branch switcher with preview (clean names: no "*", no leading spaces)
git switch $(git branch --format='%(refname:short)' | fzf --preview 'git log --oneline -20 {}')

# Include remote branches (switch creates a tracking branch from origin/x)
git branch -r --format='%(refname:short)' | fzf | sed 's#^origin/##' | xargs git switch

# Kill process interactively (SIGTERM first; -9 only if it ignores that)
kill $(ps aux | fzf --header-lines=1 | awk '{print $2}')

# Docker: exec into container
docker exec -it $(docker ps --format '{{.Names}}' | fzf) /bin/sh

# SSH to server
ssh $(grep "Host " ~/.ssh/config | awk '{print $2}' | fzf)

# Search environment variables
env | fzf

fzf Configuration

# ~/.zshrc — fzf defaults
export FZF_DEFAULT_COMMAND='fd --type f --hidden --follow --exclude .git'
export FZF_DEFAULT_OPTS='
  --height 40%
  --layout=reverse
  --border
  --info=inline
  --preview "bat --color=always --line-range :300 {}"
  --bind "ctrl-/:toggle-preview"
'
export FZF_CTRL_T_COMMAND="$FZF_DEFAULT_COMMAND"
export FZF_ALT_C_COMMAND='fd --type d --hidden --follow --exclude .git'

ripgrep is the fastest code search tool. It respects .gitignore, skips hidden and binary files by default, can search compressed files with -z, and supports full regex — all at speeds that make grep -r feel broken.

Basic Usage

CommandDescription
rg "pattern"Search current directory recursively
rg "pattern" src/Search specific directory
rg -i "pattern"Case-insensitive search
rg -w "word"Match whole words only
rg -l "pattern"List files containing matches (no content)
rg -c "pattern"Count matches per file
rg --type js "pattern"Search only JavaScript files
rg -g "*.ts" "pattern"Search files matching glob
rg -g "!*.test.*" "pattern"Exclude test files
rg -A 3 -B 2 "pattern"Show 3 lines after, 2 lines before
rg -e "p1" -e "p2"Match multiple patterns (OR)
rg "pattern" --jsonOutput as JSON (for piping)
rg -F "a.b(c)"Literal string, no regex
rg -S "pattern"Smart case: case-insensitive unless the pattern has capitals
rg -uu "pattern"Also search ignored and hidden files (-uuu adds binary)
rg --hidden -g '!.git' "pattern"Include dotfiles but not .git/
rg -U "start.*\n.*end"Multiline search
rg -P "(?<=id=)\d+"PCRE2 engine: lookaround, backreferences
rg -o "\d+\.\d+\.\d+"Print only the matched part
rg "old" -r "new"Show matches with a replacement (does not edit files)
rg --files | rg configList searchable files, filter by name
rg -tpy -Tjs "pattern"Include Python, exclude JS (rg --type-list for all types)

Real-World Searches

# Find all TODO/FIXME comments
rg "TODO|FIXME|HACK|XXX" --type-add 'code:*.{js,ts,py,go,rs}' -t code

# Find function definitions
rg "function\s+\w+" --type js
rg "def \w+" --type py
rg "func \w+" --type go

# Find imports of a specific module
rg "import.*from.*react" --type ts

# Find all API endpoints
rg "app\.(get|post|put|delete|patch)\(" --type js

# Find environment variable usage
rg "process\.env\.\w+" --type ts

# Search for a pattern, replace with sed (GNU sed; on macOS use: sed -i '')
rg -l "oldFunction" --type ts | xargs sed -i 's/oldFunction/newFunction/g'

# Filenames with spaces: NUL-separate
rg -l0 "oldFunction" | xargs -0 sed -i 's/oldFunction/newFunction/g'

# Find large files with many matches (potential refactor targets)
rg -c "any" --type ts | sort -t: -k2 -rn | head -20

ripgrep + fzf = Superpower

# Interactive code search with preview
rg --line-number --color=always "" | fzf --ansi --preview 'bat --color=always --highlight-line {2} {1}' --delimiter :

This lets you search your entire codebase interactively with a live preview of each match in context.


jq — JSON Processing

jq is the command-line JSON processor. It filters, transforms, and extracts data from JSON — essential for working with APIs, logs, and configuration files.

Basic Operations

# Pretty print
echo '{"name":"Alice","age":30}' | jq .

# Get a field
echo '{"name":"Alice","age":30}' | jq '.name'
# "Alice"

# Get nested field
echo '{"user":{"name":"Alice"}}' | jq '.user.name'
# "Alice"

# Get array element
echo '[1,2,3]' | jq '.[0]'
# 1

# Get array length
echo '[1,2,3]' | jq 'length'
# 3

Filtering and Transforming

# Filter array elements
echo '[{"name":"Alice","age":30},{"name":"Bob","age":25}]' | \
  jq '.[] | select(.age > 28)'
# {"name":"Alice","age":30}

# Map — transform each element
echo '[{"name":"Alice"},{"name":"Bob"}]' | \
  jq '[.[] | .name]'
# ["Alice", "Bob"]

# Create new structure
echo '{"first":"Alice","last":"Smith","age":30}' | \
  jq '{full_name: (.first + " " + .last), age}'
# {"full_name": "Alice Smith", "age": 30}

# Sort by field
echo '[{"name":"Bob","age":25},{"name":"Alice","age":30}]' | \
  jq 'sort_by(.age)'

# Group by field
echo '[{"dept":"eng","name":"A"},{"dept":"eng","name":"B"},{"dept":"sales","name":"C"}]' | \
  jq 'group_by(.dept) | map({dept: .[0].dept, count: length})'
# [{"dept":"eng","count":2},{"dept":"sales","count":1}]

Real-World jq Recipes

# Parse AWS CLI output — get instance IDs of running instances
aws ec2 describe-instances | \
  jq -r '.Reservations[].Instances[] | select(.State.Name == "running") | .InstanceId'

# Parse Kubernetes pods — get non-running pods
kubectl get pods -o json | \
  jq -r '.items[] | select(.status.phase != "Running") | .metadata.name'

# Parse Docker inspect
docker inspect mycontainer | \
  jq '.[0] | {id: .Id[:12], image: .Config.Image, ports: .NetworkSettings.Ports}'

# Parse npm package.json — list all dependencies
jq -r '.dependencies // {} | keys[]' package.json

# Merge JSON files
jq -s '.[0] * .[1]' defaults.json overrides.json

# Convert JSON to CSV
echo '[{"name":"Alice","age":30},{"name":"Bob","age":25}]' | \
  jq -r '["name","age"], (.[] | [.name, .age]) | @csv'

# Count occurrences in log file
cat app.log | \
  jq -r '.level' | sort | uniq -c | sort -rn

# Pass shell values in safely (never splice them into the filter string)
jq --arg name "$USER" --argjson limit 10 '[.[] | select(.owner == $name) | .id] | .[:$limit]' items.json

# Build JSON from scratch
jq -n --arg v "1.2.3" '{version: $v, tags: ["a","b"]}'

# Compact one-line output (e.g. for JSON Lines)
jq -c '.[]' items.json

# Edit a field in place (jq has no -i; write to a temp file)
jq '.version = "2.0.0"' package.json > tmp.json && mv tmp.json package.json

# Delete fields / rename keys
jq 'del(.password, .token)' user.json
jq 'with_entries(.key |= ascii_downcase)' obj.json

# Read a non-JSON line-based file
jq -R -s 'split("\n") | map(select(length > 0))' names.txt

# Fail the script if a field is missing/false/null
jq -e '.ready' status.json >/dev/null || echo "not ready"

jq Cheat Table

ExpressionDescription
.Identity (whole input)
.fieldGet object field
.[0]Get array element
.[]Iterate array elements
| Pipe to next filter
select(condition)Filter elements
map(expr)Transform each element
lengthString/array/object length
keysObject keys as array
valuesObject values as array
to_entriesObject to [{key, value}]
from_entries[{key, value}] to object
group_by(.field)Group array by field
sort_by(.field)Sort array by field
unique_by(.field)Deduplicate by field
@csvFormat as CSV
@tsvFormat as TSV
@base64Base64 encode
-r flagRaw output (no quotes)
-s flagSlurp (read all input as one array)
.field? / .[]?Suppress errors when the input isn't an object/array
a // bAlternative: b if a is null/false/missing
has("k")Key exists
del(.k)Remove a key
with_entries(f)Map over {key, value} pairs
..Recurse into every value (.. | .id? // empty)
paths / getpath(p)All paths / value at a path
addSum numbers / concatenate arrays or strings
min_by(.f) / max_by(.f)Element with smallest / largest field
test("re") / capture("(?<n>re)")Regex match / named captures (Oniguruma)
$ENV.HOME / env.HOMEEnvironment variables
@shQuote for safe use in a shell command
@json / fromjsonEncode to / decode from a JSON string
-c flagCompact output, one value per line
-n flagNo input (build JSON from --args)
-e flagExit status 1 if last output is false/null
--arg k v / --argjson k vPass a string / JSON value as $k

Common Workflows

Git Interactive Workflow

# Interactive add with preview
git add $(git diff --name-only | fzf --preview 'git diff --color=always {}' -m)

# Interactive branch delete
git branch --format='%(refname:short)' | fzf -m | xargs git branch -d

# Interactive cherry-pick from another branch
git log --oneline other-branch | fzf | awk '{print $1}' | xargs git cherry-pick

# Search git history for deleted code
git log -p --all -S 'functionThatWasDeleted' | head -50

Quick File Operations

# Find and edit all files containing a pattern
rg -l "deprecated_function" | xargs $EDITOR

# Rename files matching a pattern
fd "\.jpeg$" | while read f; do mv "$f" "${f%.jpeg}.jpg"; done

# Find large files
fd --type f --size +10m

# Count lines of code by file type
fd --type f --extension ts | xargs wc -l | sort -rn | head -20

API Testing from Terminal

# Quick API test with timing
curl -s -o /dev/null -w "HTTP %{http_code} in %{time_total}s\n" https://api.example.com/health

# POST with JSON body, pretty-print response
curl -s -X POST https://api.example.com/users \
  -H "Content-Type: application/json" \
  -d '{"name":"Alice"}' | jq .

# Follow redirects, show headers
curl -sLI https://example.com

# Fail on HTTP errors (non-zero exit on 4xx/5xx) and print the body anyway (curl 7.76+)
curl --fail-with-body -s https://api.example.com/users

Shell History That Scales

# ~/.zshrc: big, shared, de-duplicated history
HISTSIZE=100000
SAVEHIST=100000
setopt SHARE_HISTORY HIST_IGNORE_ALL_DUPS HIST_IGNORE_SPACE   # leading space = not saved

# Or replace Ctrl+R with atuin (SQLite history with context, optional sync)
eval "$(atuin init zsh)"


Test Yourself
  1. What tmux key binding splits the current pane vertically (with default prefix)? Ctrl+b %

  2. How do you detach from a tmux session without closing it? Ctrl+b d

  3. What zsh plugin provides fish-like command suggestions as you type? zsh-autosuggestions

  4. What z command jumps to a frequently used directory by partial name? z partial-name (e.g., z vault to jump to ~/projects/knowledge-vault)

  5. What fzf key binding fuzzy-searches your command history? Ctrl+R

  6. How do you search only TypeScript files with ripgrep? rg "pattern" --type ts or rg -g "*.ts" "pattern"

  7. What jq expression filters array elements based on a condition? .[] | select(.field > value)

  8. What ripgrep flag shows only filenames containing matches? rg -l "pattern"

  9. What tmux command creates a new session named "work"? tmux new -s work

  10. What jq flag gives raw output without quotes? -r

Common Gotchas

  • tmux prefix collision with readline. The default Ctrl+b conflicts with backward-char in emacs-mode shells. Remapping to Ctrl+a is easier to reach but shadows beginning-of-line; with bind C-a send-prefix you press Ctrl+a twice to get it.
  • fzf without fd as backend. The default find command is slow and includes .git directories. Set FZF_DEFAULT_COMMAND to use fd for much faster results.
  • ripgrep silently skips files. By default rg skips anything in .gitignore, hidden files and binary files, so "no matches" may just mean the file was ignored. Check with rg --debug or rg -uuu. Conversely, --no-ignore searches node_modules and build artifacts; add -g '!node_modules' to exclude them.
  • jq returns null for missing paths instead of failing. If you query .nonexistent, jq prints null with exit code 0. Use jq -e to fail on null/false, or select(. != null) to drop missing fields.
  • Aliasing find to fd or grep to rg. The flags are different, so pasted commands and muscle memory break. Aliases don't apply in scripts, but they do apply when you copy a command from a doc. Prefer the real names (fd, rg) and leave the originals alone.
  • rm -i alias as a safety net. It trains you to expect prompts, then rm on another machine (or \rm, or a script) deletes without asking. Consider trash-cli instead.

One-Liner Summary

Terminal productivity is a multiplier -- tmux gives you persistent sessions, fzf gives you fuzzy search, ripgrep gives you instant code search, and jq gives you structured JSON processing, all without leaving the command line.