Tmux scripting with copilot

Posted on Jul 13, 2023

I use tmux BTW! For development I have a session per project and try to keep things minimal. My starting setup is a window named code where I launch vim (nvim ((lvim)) and a second window named term where I do everything else. I will add new windows and panes as I need them but this is the starting point.

To speed up the tmux setup I’ve created the script below with the help of copilot. I still need to add the code to checkout the repo if I haven’t already but otherwise the script does exactly what I have outlined above.

Check it out:

#!/bin/bash

# receives a command line argument project_name and checks for the existance of a folder of the same name
# in ~/git/${project_name} if the folder does not exist then perform a git clone from the 
# repository BigAirJosh/${project_name}. Next create a tmux session (if one does not already exist)
# with the same project name.  Inside te tmuc session create a window named code, change directory 
# to ~/git/${project_name} and launch lvim.  Then create a second window named term in the same directory

project_name=$1

if [ ! -d ~/git/${project_name} ]; then
    echo "git clone not implemented"
fi

if tmux has-session -t "${project_name}" 2>/dev/null; then
  tmux attach -t "${project_name}"
else
  tmux new-session -s "${project_name}" -n code -d
  tmux send-keys -t "${project_name}:code" "cd ~/git/${project_name}" C-m
  tmux send-keys -t "${project_name}:code" "lvim README.md" C-m
  tmux new-window -t "${project_name}:2" -n 'term'
  tmux send-keys -t "${project_name}:term" "cd ~/git/${project_name}" C-m
  tmux select-window -t "${project_name}:code"
  tmux attach -t "${project_name}"
fi

Copilot was very helpful but certainly didn’t provide a working solution with only my starting comments acting as a prompt. I had a few tmux specific fixes to add and the bash variable interpolation was missing inthe tmux commands. However the bash conditionals and tmux commands selected were all spot on. This meant I was able to complete the script with referencing and tmux docs. This probably took 20 minutes to write and test before I stuck it in this post to celebrate :)