AppleScript で iTerm2 Version 3 を操作する

2016.07.07

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

ターミナル起動時にいろいろやる

iTerm はターミナルのエミュレータツールです。
様々な機能 が存在するため、ターミナルの代わりに利用している人も多いのではないでしょうか。

私は毎朝ターミナルを起動した後に以下の行動を取ります。

  1. 複数のタブを開く
  2. 全てのタブにおいて特定の(Git 管理下の)ディレクトリに移動する
  3. 全てのタブにおいて git pull を実行する

今回はこの作業を AppleScript で自動化します。

※ iTerm2 Version 3 は現在 Beta 版であり、かつ以前のバージョンとは AppleScript の書き方に互換性がありません。Version 2 以前では以下のコードは動かないのでご注意ください。

サンプルコード

set directories to {"directory-a", "directory-b", "directory-c"}
set countOfDirectories to count directories

tell application "iTerm"
    activate
    tell current window
        set firstTab to current tab

        repeat with i from 1 to countOfDirectories
            tell current session of current tab
                write text "cd ~/git/" & (item i of directories)
                write text "git pull --prune"
            end tell
            if i = countOfDirectories then exit repeat
            create tab with default profile
        end repeat

        tell firstTab
            select
        end tell
    end tell
end tell

解説

細かい部分は省略します。
詳しくは 公式ドキュメント やスクリプトエディタ 上で iTerm の用語説明を確認してください。
[スクリプトエディタ起動] - [ファイル] - [用語説明を開く...] - [iTerm.app を選択]


set directories to {"directory-a", "directory-b", "directory-c"}
set countOfDirectories to count directories

遷移したいディレクトリ名とその要素数をそれぞれ変数に代入しています。


set firstTab to current tab

現在のタブを firstTab という変数に代入しています。
これは最後に一番左のタブにフォーカスを合わせるためです。


tell current session of current tab
    write text "cd ~/git/" & (item i of directories)
    write text "git pull --prune"
end tell

タブのセッションに対してコマンドを実行しています。
write text はテキストを入力し改行を入れるという命令です。
結果、任意のコマンドが実行できます。

"cd ~/git/" & (item i of directories) では & で文字列連結を行い、cd コマンドでそのディレクトリに移動しています。
"git pull --prune" では prune オプションを追加しています。
これはリモートで削除されたブランチをローカルでも削除するというものです。


create tab with default profile

新規タブを作成しています。


tell firstTab
    select
end tell

firstTab 変数に代入したタブを選択します。
これで一番左のタブにフォーカスがあたります。


以上です。

セッションに対して write text を実行すれば任意のコマンドが入力できます。
ターミナル起動時に行う決まった作業は AppleScript で自動化してはどうでしょうか。

リンク

ミレニアム・ファルコン製作日記 #24

24 号 表紙

mfd_24_1

パーツ

mfd_24_2

mfd_24_3

mfd_24_4

成果

mfd_24_5

mfd_24_6

今回の作業は以下の 2 つでした。

  • 下部フレームを組み立てる
  • 外殻プレートを取り付ける

8 つのフレームパーツをこれまで組み立ててある骨組みに加えました。
これで船体下部半分のフレームが完成となります。
相変わらずこの作業はとても楽しい。
ネジっていいですよね。

フレームを作成した後は、それらに対して外殻プレートを仮組みしました。
徐々にファルコンっぽさが出てきています。

組み立てたパーツが巨大になってきました。
さて、どこに保管しようかな。

それではまた次回。

May the Force be with you!