Skip to content

Instantly share code, notes, and snippets.

@kalimar
Last active June 30, 2022 13:27
Show Gist options
  • Save kalimar/4512ac8d49c53d5a5561807b86f6db00 to your computer and use it in GitHub Desktop.
Save kalimar/4512ac8d49c53d5a5561807b86f6db00 to your computer and use it in GitHub Desktop.
How to add a badge to iterm2 on Zsh

Custom Badges in iTerm2

iTerm2 - the popular terminal emulator for OSX has added some really neat features. One of those, is badges. From the documentation: A badge is a large text label that appears in the top right of a terminal session to provide dynamic status, such as the current host name or git branch.

I had some trouble figuring out how to build a badge so I wanted to share a quick walk-through. Thanks to Chris Mar for teaching me.

Install shell integrations on iTerm.

Easy enough - it's an option on the dropdown menu

Open your .zshrc file and verify that the integrations are installed. iTerm should have added the line test -e "${HOME}/.iterm2_shell_integration.zsh" && source "${HOME}/.iterm2_shell_integration.zsh" .zshrc is the configuration file for Zsh and generally lives in your home directory.

Declare a custom variable in your .zshrc file

You now need to write a special function in .zshrc that Zsh understands. It looks like this:

function iterm2_print_user_vars() {
  iterm2_set_user_var bananas $(do_fun_stuff)
}

The function iterm2_print_user_vars() calls iterm2_print_user_vars() one or more times. The function iterm2_set_user_var assigns your user var bananas to do_fun_stuff, which can be written directly there or encapsulated in another function.

Finally you need to declare your user var in iterm for each profile you want to use it in.

Let's create two different examples

Display when there's a diff in your git branch

Add the following to your .zshrc:

$(git function iterm2_print_user_vars() {
  iterm2_set_user_var gitDiff $(is_git_branch_dirty)
}

function is_git_branch_dirty {
  [[ $(git diff --shortstat 2> /dev/null | tail -n1) != "" ]] && echo "⚡⚡"
}

Add \(user.gitDiff) to your badge in the profile settings.

Couldn't ready the code? Checkout this stackoverflow for the skinny on brackets in shell scripting. I found it to be quite helpful.

How to add a camel on wednesdays and an Octopus on others

function is_it_wednesday {
  if [[ $(date +%A) = "Wednesday" ]]
    then
     echo "🐪" # Camel Prompt
    else
    echo "🐙" # Inky Prompt
  fi
}

Add \(user.humpDay) to your badge in the profile settings.

Your homework is to combine two badges!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment