Use Apple­Script to Auto­mate with iTerm

Publisher: TJ Fogarty

Modified: 2018-03-13

Some­times when you’re work­ing on a project, be it work or per­son­al, you might only be run­ning a com­mand in the ter­mi­nal like npm run dev. Oth­er times it might be a bit more involved. Maybe you have a local serv­er run­ning in one tab with anoth­er tab to run web­pack and final­ly anoth­er one open for you to tap in your git commits.

This gives us an oppor­tu­ni­ty for automa­tion if you find your­self doing this often. Let’s imag­ine the above sce­nario where we want to run a serv­er, web­pack and keep a tab free for oth­er once-off com­mands that we might want to run like git.

To get start­ed, we’ll need to open Script Edi­tor from Appli­ca­tions > Util­i­ties > Script Edi­tor. We’ll use this blank can­vas to line up some instruc­tions. Note: this assumes iTerm is already running.

tell application "iTerm"
    tell the current window

    end tell
end tell

With this we grab the cur­rent­ly run­ning instance of iTerm and focus in on the cur­rent win­dow that’s running.

Next we’ll cre­ate a new tab and run some com­mands. This will set a vari­able for the tab that we can inter­act with and run with the default pro­file. If you have oth­er pro­files set up with iTerm you can spec­i­fy it here instead.

What’s nice as well is we can tell iTerm to split into panes so we don’t get over­run with tabs.

tell application "iTerm"
    tell the current window
        set appTasks to create tab with profile "Default"

        tell the appTasks
            tell the current session
                set name to "App"
                write text "cd ~/Code/my-app"
                write text "node index.js"

                set webpack to split horizontally with default profile
                tell webpack
                    write text "cd ~/Code/my-app"
                    write text "npm run dev"
                end tell
            end tell
        end tell

        set freeTab to create tab with profile "Default"

        tell freeTab
            tell the current session
                set name to "Free"
                write text "cd ~/Code/my-app"
            end tell
        end tell
    end tell
end tell

You could also use this to launch it with your code edi­tor of choice, so if you’re rock­ing Visu­al Stu­dio Code you could update the last block to be:

tell freeTab
  tell the current session
    set name to "Free"
    write text "cd ~/Code/my-app"
    write text "code ."
  end tell
end tell

Once you’re ready to go, you can click the play but­ton in the tool­bar of Script Edi­tor to kick every­thing off. When you’re hap­py with the result you can save the script and the next time you launch Script Edi­tor you’ll be able to choose it and run it again.

I’ve found this fair­ly use­ful for work where there might be mul­ti­ple apps and ser­vices that need to be run in parallel.