exupero's blog

Tmux worktree scripts

In the previous post I showed a script that creates a Tmux session for a particular directory and attaches to it. More often, however, I launch new Tmux sessions from within Tmux, especially for Git worktrees that branch from the current repository. This script does most of the work:


if [[ ! -d $directory ]]; then
  if git rev-parse --quiet --verify $branch > /dev/null; then
    git worktree add $directory $branch
    git worktree add --checkout -b $branch $directory

tmux new-session -d -c $directory -s "$session"
tmux send -t "$session" "cd $directory" C-m
tmux send -t "$session" "vim" C-m
tmux new-window -t "$session" -c $directory
tmux switch-client -t "$session:1"

If the directory doesn't exist, the script creates a new worktree. The exact worktree add subcommand depends on whether the branch already exists or needs to be created. Once it creates the directory, it creates a new Tmux session, configures it, and switches to it. I call the script workspace.

I don't invoke workspace directly. Instead it's called from a couple of wrapper scripts. One takes a branch name and generates from it the directory and session names that are then passed to workspace. The other wrapper script takes a directory name and only generates a session name (a branch name isn't needed since the existing worktree is already checked out to a branch).