iTerm2 (OS X) change background image for current window from shell?

iTerm2 allows to set a background image or color, either for the current window or the default (used for all new windows).

However, can I also set the current window's background image or color from the command line? I.e. is there some magic iTerm2 terminal command to set the active window's background?

I would love to use this in scripts to change the background reflecting that I'm logged in at certain remote systems, to make an automatic visual difference between local or remote shells, or even use specific backgrounds for ssh sessions on specific servers.


Solution 1:

I was just trying to do exactly the same :-). Here you go, using AppleScript and bit of bash if you like.

--this goes inside for example bgImgIterm.scpt--
tell application "iTerm2"
  tell current session of current window
    set background image to "/path/to/img/img.jpg" 
  end tell
end tell

then you can run it inside bash like

#!/bin/bash
osascript /path/to/scpt/bgImgIterm.scpt

My current OSX version is 10.11.5 and iTerm2 version is 3.0.10

Solution 2:

Without Using osascript, Iterm2 supports "echo command" to change the background image. Try this zsh script.

#bin/zsh!

change() {
    thumbnails='/path/to/images/folder'
    images=(`ls $thumbnails`)
    num_images=${#images[*]}
    myfilename="${thumbnails}/`echo ${images[$((RANDOM%$num_images + 1))]}`"
    echo $myfilename > $current_tty
    base64filename=`echo ""${myfilename}"" | base64`;
    echo "\033]1337;SetBackgroundImageFile=${base64filename}\a" > $current_tty;
    unset $RANDOM
}

Be aware of you have to confirm iterm2's message for the first time for all images.

And, moreover, this script will do well in tmux or even in vim.