How to add badges to 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 walking me through the process.

First, a couple of things to keep in mind. This walk-through includes code for zshell but should work for the most part, or be very similar for other popular shells like bash

Second, the emoji characters I used in the tutorial are built right into the mac keyboard. Here's a quick tutorial on how to insert them.

Here's the walk-through

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:

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 read 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!


by Kalimar Maia