Categories
Automation

Dynamic Profile And Badge Switching Without Shell Integrations In iTerm2

I use iTerm2 for all my terminal work.  One very nice feature it has is dynamic profiles.  But I usually don’t want to install shell integrations on every server.  Instead, I use my dotfiles and an SSH config to change profiles.  While working across different local, development, and production systems, it’s helps my mental state to know when I’m on a dev or prod system.  I have my system setup so when I:

  • SSH to a local vagrant box, my terminal turns purple
  • SSH to a development host, my terminal turns blue
  • SSH to a production host, my terminal turns red

Those are just my personal color preferences.  I’ll show you how to set this up and then you can adjust it to your taste.

First, create three profiles in iTerm2 and set the background color to whatever you want.

Next, edit your ~/.ssh/config.  For vagrant, set the following under localhost (setting the profile to Local)

host 127.0.0.1
    # Use LOCAL iTerm2 profile changes when you ssh into a Vagrant instance (127.0.0.1)
    # Also display a some red text so you know it's a vagrant box
    PermitLocalCommand yes
    LocalCommand echo -e "\033]50;SetProfile=Local\a" && echo -e '\033[31mVAGRANT\033[39m'

For any production systems, set it to Production.

Host jacobsalmela.com
    # Use PRODUCTION iTerm2 profile  when you ssh into a host
    PermitLocalCommand yes
    LocalCommand echo -e "\033]50;SetProfile=Production\a"

And then I have mine set up so anything not explicitly defined is considered Development:

Host *
    # Use DEVELOPMENT iTerm2 profile  when you ssh into a host
    PermitLocalCommand yes
    LocalCommand echo -e "\033]50;SetProfile=Development\a"

Next, you’ll also want to make some changes to ~/.bash_profile, so when you exit an SSH session, your regular terminal is restored.

iterm_profile() {
    # Use the default profile on my local system
    echo -ne "\033]50;SetProfile=Default\a"
    printf "\e]1337;SetBadgeFormat=%s\a" \
           $(echo -n "\(session.hostname)" | base64)
}
# After each command, append to the history file and reread it and set the iterm profile back to local
export PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND$'\n'}history -a; history -c; history -r;
iterm_profile;"

 

Leave a Reply