Search code examples
applescript

How to launch an iTerm2 profile only once (via AppleScript)


I would like to create an Apple Script which launches an iTerm2 profile exactly once. If a session of this profile is already running, the corresponding window should be focused, otherwise a new session should be launched.

My idea for the implemantation so far is

  1. loop through all windows of iTerm2 and check their name
  2. if the name matches the profile name, focus the window
  3. if none of the names matches the profile name, launch a new session with this profile

However, I haven't managed to loop over the windows and check their names against a predefined string.


Solution

  • After a lot of trial an error, I finally figured it out. The script below takes the name of the profile as the argument and does what I described in the question.

    on run argv
        set isopen to false
        set targetName to (item 1 of argv)
    
        tell application "iTerm2"
            repeat with w in windows
                set wn to name of w
                if wn = targetName then
                    set isopen to true
    
                    tell application "System Events"
                        perform action "AXRaise" of window (index of w) of process "iTerm2"
                    end tell
                    activate
    
                    exit repeat
                end if
            end repeat
    
            if not isopen then
                create window with profile targetName
            end if
        end tell
    end run