joeldueckdotcom

Terminal shortcuts using Alfred and AppleScript

I have an Alfred “workflow” for connecting to certain servers. This allows me to hit Opt+Space (the Alfred shortcut key combo), then type ws[Space] to bring up a list of servers that will autocomplete as I continue typing. When I select one, Alfred will open a new Terminal window and immediately run the commands to SSH into that server.

There are two parts to the workflow.

Input → Script filter

The first part is the Script Filter.

Set Language to /bin/bash. The script just uses cat to echo a static list of servers/commands in JSON format:

cat << EOB
{"items": [
  {
    "title": "WAC1 Mainframe",
    "subtitle": "ssh user@10.0.100.0",
    "arg": "screen -T vt100 ssh -t user@10.0.100.0 '/gobbx; bash -l'; exit",
    "autocomplete": "WAC1",
    "icon": {
      "path": "ssh.png"
    }
  },
  {
    "title": "Example.com web server",
    "subtitle": "ssh user@10.0.100.0",
    "arg": "ssh user@10.0.100.0; exit",
    "autocomplete": "example.com",
    "icon": {
      "path": "ssh.png"
    }
  }
]}
EOB

The arg portion is the command string that will be passed to the next part of the workflow when you select that option. You can see the second one is a straightforward ssh command. The first one has to be a little more elaborate since it connects to an old system: it runs ssh within screen set to use VT100 terminal emulation. I end all the commands with ; exit so that the terminal window closes when I exit the remote session.

Action → Run Script

In Alfred, the output from the script filter above should be linked to the input of a new Run Script action. This action is set to use /usr/bin/osascript and “with input as argv”.

on run argv
  set theQuery to item 1 of argv
  tell application "Terminal"
    activate
    set newTab to do script
    set current settings of newTab to settings set "Ocean"
    do script theQuery in newTab
  end tell
end run

The settings set can be set to the name of any profile in the Terminal app’s PreferencesProfiles settings.