I work on a software project where we currently have five different repositories. Every once in a while, it is necessary to test something end-to-end with all five apps running locally and pointed at each other. Getting everything set up correctly can consume a lot of time and lead to frustration. I find it hard to remember all the different environment variables I need to set and the different terminal commands required for each app. I also have to arrange my iTerm2 windows and tabs in a way that makes sense to me each time. After doing this arduous process one too many times, I figured there must be a better way.
At this point, I’d gotten a little experience with bash scripts that we use in our project. I thought maybe I could do something similar so I could just run a single script to get everything set up and running. I talked to my manager, Joe Chrysler, and he told me I should look into scripting my iTerm2 terminal. After doing some research, I found that iTerm2 has a Python API that you can use to write some really useful scripts! Here is the documentation I used. After some experimentation, here are the two most useful features I found.
iTerm2 allows long-running process.
For my purposes I need to run a command in a terminal window like
docker compose-up or
make dev and then leave that tab open and running so I can monitor and also run other commands in different tabs and windows. If you wish to do something like this, when creating a script choose “Long-running Daemon” when prompted.
You can script iTerm2 to open new windows and tabs for you.
I prefer to start my script in the current window I’m in, so I start with this:
Then, I send the commands I want for that window like this:
You’ll notice that, in this script, I use `session.async_split_pane(vertical=true)` to split my current window in two. The first pane has Docker running, and the second has the app running. This allows me to monitor both panes in one iTerm2 window.
For my example case, I need five different apps running. How I decided to organize this for myself was to have five different windows for each of the apps and to have separate panes for each command needed to get each app running inside of the five relevant windows. I accomplished this by using this command:
After opening a new window that you want to start sending text to, remember to grab the current window again by running this:
I hope these tips about iTerm2 scripts will help you further automate your workflow. I know having a few of these scripts has already saved me quite a bit of time on my project!