TIL you can set iTerm 2 tab colors programmatically

Oliver Peate posted on August 25th, 2020

iTerm2 has proprietary escape codes which allow you to set the tab color programmatically (and other fancy things). In combination with ZSH’s change directory hook (chpwd) this means we can set the color each time the directory changes.

With a script which consistently produces the same color for a given directory, we can visually group tabs together.

# In your ~/.zshrc or similar

add-zsh-hook chpwd (){ /usr/local/bin/tab_color }
/usr/local/bin/tab_color

And the/usr/local/bin/tab_color script:

#!/usr/bin/env ruby --disable-gems

require "digest"

seed = Digest::SHA256.hexdigest(Dir.pwd).hex
generator = Random.new(seed)

# https://iterm2.com/documentation-escape-codes.html
["red", "green", "blue"].each do |color|
  print "\033]6;1;bg;#{color};brightness;#{generator.rand(0..255)}\a"
end

Performance

With --disable-gems specified the Ruby script takes ~0.09s to run, so it doesn’t noticeably slow changing directory.

repeat 5 { time tab_color }

tab_color  0.03s user 0.04s system 89% cpu 0.082 total
tab_color  0.03s user 0.04s system 88% cpu 0.085 total
tab_color  0.03s user 0.04s system 86% cpu 0.087 total
tab_color  0.03s user 0.04s system 87% cpu 0.087 total
tab_color  0.03s user 0.04s system 87% cpu 0.086 total

What did you learn today?

Write a quick TIL post to reflect on what you've learned.

Write a post