Last Updated: September 27, 2021
·
14.64K
· Lorin Hochstein

Launch iTerm2 and run commands in tabs

You can use AppleScript to start up iTerm2 and run commands in different tabs. This is helpful if you want to script the startup of an app that involves multiple services that you are going to run in the foreground for development (e.g., rails server, sidekiq, redis, ...).

This AppleScript example will change directory to ~/dev/myapp and run "make foo" in one tab and "make bar" in the other.

Create and save this file in AppleScript editor:

tell application "iTerm"
    activate
    set myterm to (make new terminal)
    tell myterm
        launch session "Default Session"
        tell the last session
            write text "cd ~/dev/myapp"
            write text "make foo"
        end tell
        launch session "Default Session"
        tell the last session
            write text "cd ~/dev/myapp"
            write text "make bar"
        end tell
    end tell
end tell

If you save this as run.scpt, you can then run it at the command line by doing:

$ osascript run.scpt

Related protips:

Use ⌥ ← and ⌥→ to jump forwards / backwards words in iTerm 2, on OS X