Automating iTerm2
Tags: terminal, applescript, osascript, automation
Published: 2022-03-25 22:40:18

---
title: Automating iTerm2
published: true
description: Automating opening iTerm tabs and windows, navigating to directories, and starting services with Applescript
tags: terminal, applescript, osascript, automation
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x7x1tiysufctjyd718qc.jpg
 
---

## TLDR
Working with localhost and multiple repos can be tedious - Apple has a way to automate opening multiple terminal windows and tabs, navigating to the directories that you need, and starting up those services. This is a tutorial to show you how to set up that process.

1. [TLDR](#tldr)
2. [Why Automate?](#why-automate)
38. [came in for the save!]()
3. [Start with the Basics](#start-with-the-basics)
4. [Creating Multiple Sessions](#creating-multiple-sessions)
  - [What is happening?](#what-is-happening)
5. [Adding to the Script](#adding-to-the-script)
  - [`tell <SESSION> to write text "<COMMANDS>"`](#-raw-tell-ltsessiongt-to-write-text-ltcommandsgt-endraw-)
6. [Create a New Tab](#create-a-new-tab)
7. [Miscellaneous Settings](#miscellaneous-settings)
  - [Adding Tab Names](#adding-tab-names)
  - [Open the Terminal in Fullscreen](#open-the-terminal-in-fullscreen)
  - [Add as a a `.zsh` alias](#add-as-a-raw-zsh-endraw-alias)
8. [Wrapping Up](#wrapping-up)

## Why Automate?
For me, automation is just about speeding up the process. An example of my work flow looks like:

- Opening up iTerm
- Navigating to my frontend directory
  - start the frontend server
- Split the terminal vertically, navigate the the frontend directory
  - start webpack
- Open a new tab, navigate to the reporting directory
  - start the reporting service
- Open a new tab, navigate to the engine directory 
  - start the engine service (this is a Docker service, with the help of aliases, has been reduced to smaller commands)

It may not seem like a whole lot, but it becomes a pain whenever I have to restart my computer and have to restart each of those services needed to run the application. When I discovered that it could be automated, it changed everything.

[Applescript](https://developer.apple.com/library/archive/documentation/AppleScript/Conceptual/AppleScriptLangGuide/introduction/ASLR_intro.html) came in for the save!

## Start with the Basics
Let's start with a simple script to get the hang of the syntax.

- Create a file `hello_world.scpt` with the content below:
```
#!/usr/bin/osascript
tell application "iTerm2"
  tell current session of current tab of current window
    write text "echo 'hello world!'"
  end tell
end tell
```
- From the directory you created `hello_world.scpt`, Run the script like this: `osascript hello_world.scpt`. You should see:

![Echoing hello world in iTerm with Applescript automation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ud8sx7q3rbfju9gnibhj.png)

Why does it appear twice? Echoing added the command to the terminal history. If you hit up in the terminal, `echo 'hello world!` will appear as the last command.

If you hit up again, you'll get your first command, `osascript hello_world.scpt`.

## Creating Multiple Sessions
Now for the workflow automation. 

- Create a new script file called `create_sessions.scpt` with the content below:

```
#!/usr/bin/osascript
tell application "iTerm2"
  set serverSession to current session of current window

  tell serverSession
    set webpackSession to (split vertically with default profile)
  end tell
end tell
```

- From the directory you created `create_sessions.scpt`, Run the script like this: `osascript create_sessions.scpt`. You should see the terminal window spilt vertically.

![New terminal session and splitting the window vertically](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/39a8at8mof46ahk4fhnj.gif)

### What is happening?
Let's break it down:

- `tell application "iTerm2"`: which application we're sending commands to. In this case, iTerm2 (this can also be iTerm).
- `set serverSession to current session of current window`: is creating a new variable name for the current active window. In this case, `serverSession` is being assigned to the current window. I used `serverSession` since this will be the window that I used to run my server.
  - `set <NAME> to current session of current window`
- `set webpackSession to (split vertically with default profile)`: sets a new variable `webpackSession`, and splits the window vertically (`vertically` can be swapped for `horizontally` to match your needs).
- `end tell`: "closing tag" for the function

## Adding to the Script

```
#!/usr/bin/osascript
tell application "iTerm2"
  set serverSession to current session of current window

  tell serverSession
    write text "cdkwhub"
    set webpackSession to (split vertically with default profile)
  end tell

  tell webpackSession
    write text "cdkwhub"
  end tell
end tell
```

### `tell <SESSION> to write text "<COMMANDS>"`
Here's where the automation fun happens. With each `write text`, we can pass in the commands that we need. For me, `cdkwhub` is an alias that `cd`'s into my codebase directory. 

In the next tell block, we reference the new tab that was created and write a command to that window.

![Writing commands to each tab](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iajzbb017a3tjw3bocjh.gif)
 
## Create a New Tab
Continuing to add to the script,

```
  tell current window
    create tab with default profile
    set tab2 to current session
  end tell

  tell tab2
    write text "put a command here"
  end tell
```

- `tell current window`: with the vertical tab selected
  - `create tab with default profile`: iTerm will create a new tab 
- `set tab2 to current session`: creates a new variable called `tab2` and sets it to the new session
- `tell tab2`: in the new tab, it writes text 

![Opening split tab and new tab](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ox79eh9petoqvrl0meb9.gif)
 
## Miscellaneous Settings

### Adding Tab Names
One thing you can do to make your tabs more organized is to set a tab to them. To set a name, use `set name to "name"`. You can do that like so:

```
...
  tell serverSession
    set name to "SERVER" # Add this line 
    write text "cdkwhub"
    set webpackSession to (split vertically with default profile)
  end tell
...
```
Inside of each tell statement you can set a name.

### Open the Terminal in Fullscreen
Another thing you can automate with this script is having it open your window in fullscreen. You can do that by adding the following to the top of the script:

```
...
tell application "iTerm2"
  # Open window in full screen
  tell application "System Events"
    keystroke "f" using {control down, command down}
  end tell
...
```

### Add as a `.zsh` alias
You can really put your automation in overdrive by creating an alias to run your new script. Using an alias can simplify your command into one single word. An example of my use looks like this:

```
export SCRATCH_DIR=~/codebase/scratch
alias cdscratch='cd $SCRATCH_DIR';
alias startrepos='cdscratch; osascript create_sessions.scpt'
```
_[Creating `zsh` aliases](https://linuxhint.com/configure-use-aliases-zsh/)_

- Create a variable to the directory that has my script
- Create an alias that navigates into that directory
and finally, the whole thing
- Create an alias that uses the `cd`ing alias, and then add the `osascript` command followed by the name of the file 

When you open a terminal window, entering `startrepos` followed by enter will fire off the automation script.

## Wrapping Up
Hopefully this helps you save some time. You can also use the [Script Editor](https://support.apple.com/guide/script-editor/welcome/mac) application to write the script and export it as an executable application, as well as other miscellaneous things. You can also use it to automate other aspects of your day to day processes.

#### Helpful Likes
- [Final script](https://gist.github.com/cweave/1d654415ef95eda3293883ee6298cfb5)
- [Applescript](https://developer.apple.com/library/archive/documentation/AppleScript/Conceptual/AppleScriptLangGuide/introduction/ASLR_intro.html) documentation 
- [iTerm2 Applescript](https://iterm2.com/documentation-scripting.html) documentation 
- [Creating `zsh` aliases](https://linuxhint.com/configure-use-aliases-zsh/use-aliases-zsh/)