Auto-Update iTerm2 Badge with Zsh to Show Current Directory
This guide explains how to configure iTerm2's badge to automatically display the current folder name and update instantly when you change directories, using a simple Zsh hook and Base64‑encoded OSC 1337 control sequences.
Use Cases and Pain Points
Developers often open multiple iTerm2 windows or tabs and switch between projects, making it easy to lose track of the current directory. Accidentally running scripts in the wrong folder can cause serious problems, such as deleting production data when intending to clean a test environment.
What Is iTerm2 Badge
The iTerm2 badge is a small piece of text shown in the upper‑right corner of a terminal window, used to convey context like project name, directory, Git branch, or environment without occupying command‑line space.
Implementation Overview
iTerm2 provides the OSC 1337 control sequence, where the SetBadgeFormat command sets the badge content. The content must be Base64‑encoded. The implementation consists of three steps: obtain the full path, extract the last directory name, encode it in Base64, and send it via the control sequence.
Recommended Solution: Automatic Update with Zsh
In macOS's default Zsh environment, the chpwd hook can trigger the badge update whenever the directory changes. Adding a small function and hook to ~/.zshrc does not affect startup speed and requires no extra installation.
function iterm_set_badge() {
if [[ "$TERM_PROGRAM" == "iTerm.app" ]]; then
printf "\e]1337;SetBadgeFormat=%s\a" "$(basename "$PWD" | base64)"
fi
}
autoload -Uz add-zsh-hook
add-zsh-hook chpwd iterm_set_badge
iterm_set_badgeAfter adding this configuration, the badge instantly reflects the current directory, e.g., showing funtester when in ~/projects/funtester and updating to user-service after cd ~/projects/user-service.
Conclusion
The badge provides a silent, always‑visible cue of your working context, eliminating the need to repeatedly check pwd or parse prompts. It’s a lightweight, high‑impact tweak that can be extended to display Git branch status, environment tags, or even integrate with tmux for a more context‑aware terminal experience.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
