Skip to content

Instantly share code, notes, and snippets.

@mprokopov
Created February 22, 2026 06:41
Show Gist options
  • Select an option

  • Save mprokopov/49e9476bd3aedd1e05c08c55681e5208 to your computer and use it in GitHub Desktop.

Select an option

Save mprokopov/49e9476bd3aedd1e05c08c55681e5208 to your computer and use it in GitHub Desktop.
iTerm2 + Zsh optimization for Claude Code
#!/bin/bash
# Shell Startup Benchmark Script
# Measures zsh startup time to validate optimization improvements
echo "🔍 Benchmarking shell startup time..."
echo "Running 10 iterations to calculate average..."
echo ""
total_time=0
iterations=10
for i in $(seq 1 $iterations); do
# Time the shell startup by executing a simple command
time_ms=$((/usr/bin/time -p zsh -i -c exit 2>&1) | grep real | awk '{print $2}')
# Convert to milliseconds for easier reading
time_in_ms=$(echo "$time_ms * 1000" | bc)
echo "Run $i: ${time_in_ms}ms"
# Add to total (using bc for floating point)
total_time=$(echo "$total_time + $time_ms" | bc)
done
# Calculate average
avg_time=$(echo "scale=3; $total_time / $iterations" | bc)
avg_time_ms=$(echo "$avg_time * 1000" | bc)
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Results:"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Average startup time: ${avg_time}s (${avg_time_ms}ms)"
echo ""
# Provide feedback based on results
if (( $(echo "$avg_time < 0.5" | bc -l) )); then
echo "✅ Excellent! Your shell startup is very fast."
echo " This is optimal for Claude Code workflows."
elif (( $(echo "$avg_time < 1.0" | bc -l) )); then
echo "⚠️ Moderate. Your shell startup is acceptable."
echo " Consider applying lazy-loading optimizations."
else
echo "❌ Slow. Your shell startup needs optimization."
echo " Apply the optimizations from optimized-zshrc-snippets.sh"
fi
echo ""
echo "Optimization targets:"
echo " - Fast: <500ms (optimal)"
echo " - Moderate: 500-1000ms (acceptable)"
echo " - Slow: >1000ms (needs optimization)"
echo ""
echo "Common improvements:"
echo " - Lazy-load NVM: saves 500-1000ms"
echo " - Cache completions: saves 100-300ms"
echo " - Lazy-load tool completions: saves 50-200ms per tool"

iTerm2 Setup Guide for Claude Code

Complete configuration guide to optimize iTerm2 for Claude Code workflows, Terraform development, and terminal productivity.

Table of Contents


Font Installation

Recommended Fonts

Install one of these monospace fonts with excellent ligature support:

1. JetBrains Mono (Recommended)

brew install --cask font-jetbrains-mono

2. Fira Code

brew install --cask font-fira-code

3. Cascadia Code

brew install --cask font-cascadia-code

Font Configuration

  1. Open iTerm2 → PreferencesProfilesText
  2. Set Font: JetBrains Mono (or your choice)
  3. Set Size: 13-14 (adjust for your display)
  4. Enable Use ligatures (improves code readability)
  5. Enable Anti-aliased
  6. Set weight: Regular for main text, Bold for bold

Color Scheme Setup

Recommended Schemes

Choose a color scheme optimized for long coding sessions:

1. Gruvbox Dark (Recommended)

# Download and import
curl -L https://raw.githubusercontent.com/mbadolato/iTerm2-Color-Schemes/master/schemes/Gruvbox%20Dark.itermcolors -o /tmp/Gruvbox-Dark.itermcolors
open /tmp/Gruvbox-Dark.itermcolors

2. Tokyo Night

curl -L https://raw.githubusercontent.com/mbadolato/iTerm2-Color-Schemes/master/schemes/Tokyo%20Night.itermcolors -o /tmp/Tokyo-Night.itermcolors
open /tmp/Tokyo-Night.itermcolors

3. Dracula

curl -L https://raw.githubusercontent.com/mbadolato/iTerm2-Color-Schemes/master/schemes/Dracula.itermcolors -o /tmp/Dracula.itermcolors
open /tmp/Dracula.itermcolors

Color Settings

Preferences → Profiles → Colors

  • Minimum contrast: 3-4 (readable but not harsh)
  • Enable Smart Cursor Color
  • Enable Use bright colors for bold text

Status Bar Configuration

Add useful information to your terminal status bar.

Setup Steps

  1. Preferences → Profiles → Session
  2. Enable Status bar enabled
  3. Click Configure Status Bar
  4. Drag these components to the Active Components area:
    • Current Directory (shows working directory)
    • CPU Utilization (monitor performance)
    • Memory Utilization (track resource usage)
    • git state (if in a git repo)
    • Clock (optional, useful for time tracking)

Recommended Layout

[Current Directory] | [git state] | CPU: 23% | MEM: 45% | 14:23

Shell Integration

Enable iTerm2's shell integration for command tracking and better navigation.

Install Shell Integration

curl -L https://iterm2.com/shell_integration/zsh -o ~/.iterm2_shell_integration.zsh

Add to ~/.zshrc

# iTerm2 shell integration (enables command tracking, badges, marks)
test -e "${HOME}/.iterm2_shell_integration.zsh" && source "${HOME}/.iterm2_shell_integration.zsh"

# Custom window title showing current directory
if [ $ITERM_SESSION_ID ]; then
  # Show directory name in tab title
  precmd() {
    echo -ne "\033]0;${PWD##*/}\007"
  }
fi

Enable Features

Preferences → Profiles → Terminal

  • Enable Show mark indicators (left margin)
  • Enable Automatically log session input
  • Set Semantic History: Open with default app

Keyboard Shortcuts

Essential Shortcuts for Claude Code

Split Panes

  • ⌘+D - Split vertically (side-by-side comparison)
  • ⌘+Shift+D - Split horizontally (stacked view)
  • ⌘+] - Next pane
  • ⌘+[ - Previous pane
  • ⌘+Option+Arrow - Navigate split panes
  • ⌘+Shift+Enter - Maximize active pane

Navigation

  • ⌘+Shift+H - Paste history (repeat commands)
  • ⌘+; - Autocomplete from history
  • ⌘+Shift+/ - Find cursor (when lost in output)
  • ⌘+Option+B - Instant Replay (rewind terminal output)
  • ⌘+Shift+A - Select output of last command

Selection

  • ⌥+Click - Move cursor to click position
  • Triple-click - Select full wrapped lines
  • ⌘+/ - Highlight cursor

Custom Key Bindings

Preferences → Keys → Key Bindings

Add these useful bindings:

  1. ⌘+K → Send Text: clear\n (clear screen)
  2. ⌘+Shift+K → Clear Buffer (nuclear clear)
  3. ⌘+T → New Tab with Current Profile

Profile Setup

Create a Terraform Profile

  1. Preferences → Profiles → General

  2. Click + to create new profile

  3. Configure:

    • Name: "Terraform Infrastructure"
    • Command: /bin/zsh --login
    • Working Directory: /Users/[username]/[your-terraform-repo]
    • Badge: "🏗️ TF" (visual indicator)
  4. Window Tab

    • Columns: 140+ (wider windows for Claude's output)
    • Rows: 40+ (more context visible)
    • Transparency: 5-10% (optional, helps with reference)
    • Blur: Light (if using transparency)
    • Enable Keep background colors opaque
  5. Session Tab

    • Enable Automatically log session input to: ~/terraform-logs/session-{date}-{time}.log

Window Arrangements for Terraform Work

Save custom layouts for common workflows:

1. Planning Layout (3 panes)

+----------------+--------+
|                |  Vault |
|  Main          |  AWS   |
|  (tg plan)     |  Logs  |
|                |        |
+----------------+--------+
|  File Explorer          |
+-------------------------+

2. DNS Work Layout (2 panes)

+----------------+--------+
|  DNS Directory | CF API |
|  (tg apply)    | Logs   |
+----------------+--------+

3. Debugging Layout (4 quadrants)

+-------------+-------------+
| Main        | State       |
| (commands)  | (terraform) |
+-------------+-------------+
| Logs        | Docs        |
| (errors)    | (reference) |
+-------------+-------------+

To Save: Window → Save Window Arrangement → Name it (e.g., "TF Planning") To Load: Window → Restore Window Arrangement → Select saved layout


Performance Settings

Advanced Optimizations

Preferences → Advanced (search for these):

  1. "Number of scrollback lines" → 10000

    • Balances history with performance
  2. "Use Metal renderer" → Yes

    • Better GPU acceleration
  3. "GPU Rendering" → Yes (if available)

    • Significant performance boost
  4. "Instant Replay memory" → 4-8 MB

    • Useful for reviewing Claude's output
  5. "Amount to dim inactive split panes" → 0.15

    • Visual separation without distraction

Copy/Paste Behavior

Preferences → General → Selection

  • Enable Copy to pasteboard on selection (QuickCopy)
  • Enable Applications in terminal may access clipboard
  • Enable Triple-click selects full wrapped lines
  • Enable Include trailing newline when copying

Quick Tips

Productivity Shortcuts

  • ⌘+Shift+O - Open quickly (search all sessions)
  • ⌘+Option+E - Expose all tabs
  • ⌘+Shift+I - Broadcast input to all panes in tab
  • ⌘+F - Find in terminal (with regex support)

Claude Code Specific

  • Use wide windows (140+ columns) for better code display
  • Enable status bar to track git state during operations
  • Save window arrangements for common Claude workflows
  • Use split panes to compare "before" and "after" states
  • Enable session logging for audit trails

Terraform Workflows

  • Keep a dedicated "Terraform" profile
  • Use vault-aws-env function before terraform commands
  • Split panes: main (terraform), side (logs/state)
  • Enable badges to identify which workspace you're in

Troubleshooting

Font Issues

If ligatures don't work:

  1. Restart iTerm2 after font installation
  2. Check font name exactly matches (case-sensitive)
  3. Try different font variant (Regular vs Normal)

Performance Issues

If terminal feels slow:

  1. Reduce scrollback lines to 5000
  2. Disable transparency and blur
  3. Clear session history: Edit → Clear to Start of Session
  4. Check background processes with top or htop

Color Issues

If colors look wrong:

  1. Check Minimum Contrast isn't too high
  2. Disable "Use bright colors for bold text"
  3. Try a different color preset
  4. Verify terminal reports as xterm-256color: echo $TERM

Next Steps

  1. Install and configure one of the recommended fonts
  2. Import a color scheme
  3. Set up shell integration
  4. Create a Terraform profile
  5. Configure status bar
  6. Save your first window arrangement
  7. Run the benchmark-shell.sh script to measure improvements

Resources

Created for Claude Code - Optimized terminal setup for AI-assisted development workflows.

#!/bin/zsh
# Claude Code Terminal Optimizations for Zsh
# Extract these snippets into your ~/.zshrc for faster shell startup and better Claude Code integration
# =============================================================================
# 1. FAST COMPLETION INITIALIZATION
# =============================================================================
# Initialize completions once after all fpaths are set
# Check cache once per day for faster startup (speeds up shell by ~100-300ms)
autoload -Uz compinit
if [[ -n ${ZDOTDIR}/.zcompdump(#qN.mh+24) ]]; then
compinit
else
compinit -C
fi
# =============================================================================
# 2. LAZY-LOADING NVM (Node Version Manager)
# =============================================================================
# Loads NVM only when first used, saving ~500-1000ms on shell startup
export NVM_DIR="$HOME/.nvm"
nvm() {
unset -f nvm
[ -s "/opt/homebrew/opt/nvm/nvm.sh" ] && \. "/opt/homebrew/opt/nvm/nvm.sh"
nvm "$@"
}
# Auto-detect node version from .nvmrc when cd'ing into directories
autoload -U add-zsh-hook
load-nvmrc() {
if [[ -f .nvmrc && -r .nvmrc ]]; then
nvm use &>/dev/null || nvm install &>/dev/null
fi
}
add-zsh-hook chpwd load-nvmrc
# =============================================================================
# 3. LAZY-LOADING LABCTL COMPLETIONS
# =============================================================================
# Only load completions when labctl is actually used
if command -v labctl &>/dev/null; then
labctl() {
unfunction labctl
source <(labctl completion zsh)
labctl "$@"
}
fi
# =============================================================================
# 4. CLAUDE CODE SHELL OPTIMIZATIONS
# =============================================================================
# Enable better error messages for command failures
setopt no_nomatch # Don't error on unmatched globs (helpful for Claude's commands)
setopt interactive_comments # Allow comments in interactive shells
# Fast directory navigation (works great with Claude's cd suggestions)
setopt auto_cd # Type directory name to cd into it
setopt auto_pushd # Make cd push old directory onto stack
setopt pushd_ignore_dups # Don't push duplicates
# History configuration for better Claude context
HISTFILE=~/.zsh_history
HISTSIZE=50000
SAVEHIST=50000
setopt extended_history # Add timestamps to history
setopt hist_ignore_dups # Don't record duplicates
setopt hist_ignore_space # Don't record commands starting with space
setopt share_history # Share history between sessions
# =============================================================================
# 5. TERRAFORM/TERRAGRUNT ALIASES
# =============================================================================
# Quick shortcuts for Terraform/Terragrunt workflows
alias tg='terragrunt'
alias tgp='terragrunt plan'
alias tga='terragrunt apply'
alias tgd='terragrunt destroy'
alias tgi='terragrunt init'
alias tgv='terragrunt validate'
# =============================================================================
# 6. CREDENTIAL HELPER FUNCTIONS
# =============================================================================
# Quick credential setup for local terraform work
# Requires: 1Password CLI (op)
vault-aws-env() {
export VAULT_TOKEN=$(op read --account my.1password.com "op://IT-Premium/Vault root token/credential")
export AWS_PROFILE=mprokopov
echo "✓ Vault token and AWS profile set"
}
# Quick Cloudflare token for DNS work
cf-env() {
export TF_VAR_cloudflare_api_token=$(op read 'op://Private/Cloudflare API Token All Zones/password')
echo "✓ Cloudflare API token set"
}
# =============================================================================
# 7. iTERM2 SHELL INTEGRATION (Optional but Recommended)
# =============================================================================
# Enables command tracking, badges, marks in iTerm2
test -e "${HOME}/.iterm2_shell_integration.zsh" && source "${HOME}/.iterm2_shell_integration.zsh"
# Custom window title showing current directory
if [ $ITERM_SESSION_ID ]; then
function iterm2_print_user_vars() {
# Add custom badges for Claude Code context
if [[ -n $CLAUDE_SESSION_ID ]]; then
iterm2_set_user_var claude_active "🤖"
fi
}
# Show directory name in tab title
precmd() {
echo -ne "\033]0;${PWD##*/}\007"
}
fi
# =============================================================================
# USAGE NOTES
# =============================================================================
# 1. Place these snippets in your ~/.zshrc
# 2. Adjust paths and credentials references to match your setup
# 3. Run `benchmark-shell.sh` to measure startup time improvements
# 4. Expected improvements: 500-1500ms faster shell startup
# 5. Most gains come from lazy-loading NVM and caching completions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment