AppleScript: Failure to create new iTerm2

applescriptautomatoritermterminal

I have the following AppleScript code in a Run AppleScript action in Automator:

on run {input, parameters}
    set appName to "iTerm"
    if application appName is not running then
        tell application appName to activate
    end if
    tell application "iTerm"
        tell current session of current tab of current window
            write text "cd Desktop"
            split horizontally with default profile
            split vertically with default profile
        end tell
        tell second session of current tab of current window
            write text "whoami"
        end tell
        tell third session of current tab of current window
            write text "ls -al"
            split vertically with default profile
        end tell
        tell fourth session of current tab of current window
            write text "echo Hello World"
        end tell
    end tell
    return input
end run

However the application runs okay only if there is an iTerm instance already open. It will not open a new one for me.

How should I modify it so that it spins up a new iTerm window and executes the four session split and command execution?

Best Answer

Right after tell application "iTerm" add:

if (window count) is equal to 0 then reopen

This will open a new window if none are open but iTerm is running.


You can also use the following example AppleScript code to make sure window 1 exists before continuing, if one wasn't already open.

if (window count) is equal to 0 then
    reopen
    repeat until exists window 1
        delay 0.01
    end repeat
end if

By the way, if window 1 exists but is minimized, your code will still run in the minimized window. If that's an issue, then you'll need to code for that scenario or just always open a new window to run your code in, e.g:

set myWindow to (create window with default profile)
repeat until exists myWindow
    delay 0.01
end repeat