Scripting iTerm with AppleScript

Posted by rue, Wed Mar 12 04:46:00 UTC 2008

After a short embarrassment with SSH I decided I needed a bit of xtermcontrol functionality. On the rest of my machines, I use it to automatically switch to a green background when in an SSH session among other things.

As a complete newb, AppleScript syntax is a bit confusing. The idea is clear, the implementation seems somewhat awkward (particularly since I saw no way to dynamically determine properties.) So I chose to use the rb-appscript abstraction, installed through Gems. It enables accessing a high-level AppleScript-equivalent in Ruby. With this, I created the initial frail and simple draft:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# ~/Scripts/iterm.rb

require 'rubygems'
require 'appscript'

include Appscript

# Map some values or just pass-through
def expand(property)
  case property
  when 'bg'
    'background_color'
  else
    property
  end
end

include Appscript
app('iTerm').current_terminal.current_session.send(expand(ARGV.first)).set(ARGV.last)

This allows, for example, changing the background color with `ruby ~/Scripts/iterm.rb bg blue` etc.

To hook it up, I set up a function in my ~/.bashrc.osx (which is sourced in ~/.bashrc obviously):

1
2
3
4
5
6

  ssh() {
    ruby ~/Scripts/iterm.rb bg blue
    command ssh "$@"
    ruby ~/Scripts/iterm.rb bg black
  }

Obviously a lot of room for improvement but it just wraps any ssh invocation by first changing the bg, then launching ssh itself with whatever arguments were given and then switching back when ssh exits (whether requested or through an error.)

Gives me a nice blue background to easily distinguish ssh sessions among my terminals. This is exceptionally handy to use for su sessions if you use those. It is much harder to accidentally leave a bright red terminal session running than a regular-looking one. (I always only use sudo anyway, but not everyone does.)

Filed Under: mac | Tags:

Comments

Have your say

A name is required. You may use HTML in your comments.