Back when I first learnt tmux, I realized it was a really valuable tool. Soon afterwards, I found myself in need of wanting to make a split only to find out I wasn’t in tmux. This would lead to:

In pursuit of an ideal solution, I added a tiny script in my scripts directory which was called by my bashrc.

Current Workflow

My current workflow simply starts by opening the terminal. Instead of the bash prompt, I am greeted by this.

Choose the terminal to attach:
1 - 12: 3 windows (created Wed Sep 30 14:26:37 2020) (attached)
2 - tana: 3 windows (created Wed Sep 30 18:17:24 2020) (attached)
3 - userbot: 1 windows (created Tue Sep 29 18:37:19 2020)
4 - ytc: 1 windows (created Tue Sep 29 18:37:19 2020)

Create a new session by entering a name for it

At this point, I either

Implementation

In my .bashrc, live these lines.

if [[ ! -v TMUX && $TERM_PROGRAM != "vscode" ]]; then
	tmux_chooser && exit
fi

Although I use vim as my sole editor, I needed to demo something in VSCode and for that case I have added an exception so that the script does not run the tmux_chooser in VSCode’s integrated terminal.

Here is the source of tmux_chooser called above.

#!/usr/bin/bash
# shellcheck disable=SC2207

# Doesn't let you press Ctrl-C
function ctrl_c() {
	echo -e "\renter nil to drop to normal prompt"
}

trap ctrl_c SIGINT

no_of_terminals=$(tmux list-sessions | wc -l)
IFS=$'\n'
output=($(tmux list-sessions))
output_names=($(tmux list-sessions -F\#S))
k=1
echo "Choose the terminal to attach: "
for i in "${output[@]}"; do
	echo "$k - $i"
	((k++))
done
echo
echo "Create a new session by entering a name for it"
read -r input
if [[ $input == "" ]]; then
	tmux new-session
elif [[ $input == 'nil' ]]; then
	exit 1
elif [[ $input =~ ^[0-9]+$ ]] && [[ $input -le $no_of_terminals ]]; then
	terminal_name="${output_names[input - 1]}"
	tmux attach -t "$terminal_name"
else
	tmux new-session -s "$input"
fi
exit 0