Open the same terminal without switching spaces

applescriptitermspacesterminal

I'm looking for an AppleScript (or anything, really) that will do the following:

  • If a Terminal window is open in the current space, bring it to the front.
  • If not, open a new one in the current space.

I don't want it to switch to another space if a Terminal window happens to be open there.

Using iTerm2 instead of Terminal is fine, if that makes things easier :).

I've been looking around for scripts that do this, but the closest I could find is one that opens a new Terminal every time. I don't want that, because I probably have a session that I want to return to.

Best Answer

I've been working at this for a while, and controlling spaces–with or without GUI scripting, which I don't use since it's inelegant and breaks–is really hard. AppleScript lacks functions needed to properly control spaces. What can be hacked together through shell scripts and writing to/from files can't even do what's needed.

Here's what I could manage:

tell application "Terminal"
    if not application "Terminal" is running then
        activate
    else
        if (exists window 1) then
            activate
        else
            do script ""
            activate
        end if
    end if
end tell

This script does:

  • If a Terminal window is open, bring it to the front.
  • If not, open a new one in the current space.

It does not:

  • Check only within the current space when testing for an open window