Skip to content

Instantly share code, notes, and snippets.

@tistaharahap
Created August 3, 2026 08:33
Show Gist options
  • Select an option

  • Save tistaharahap/2e5ccacdd29dc6a554db1a73f1948457 to your computer and use it in GitHub Desktop.

Select an option

Save tistaharahap/2e5ccacdd29dc6a554db1a73f1948457 to your computer and use it in GitHub Desktop.
Named tmux sessions
#!/usr/bin/env bash
if ! command -v tmux &>/dev/null; then
echo "tmux is not installed." >&2
exit 1
fi
new_session() {
read -rp "Session name (blank for auto): " name
if [ -n "$TMUX" ]; then
if [ -z "$name" ]; then
tmux new-session -d
tmux switch-client -l
else
tmux new-session -d -s "$name" && tmux switch-client -t "$name"
fi
else
if [ -z "$name" ]; then
tmux new-session
else
tmux new-session -s "$name"
fi
fi
}
attach_session() {
local target="$1"
if [ -n "$TMUX" ]; then
tmux switch-client -t "$target"
else
tmux attach-session -t "$target"
fi
}
sessions=$(tmux list-sessions 2>/dev/null)
if [ -z "$sessions" ]; then
echo "No existing tmux sessions."
echo ""
new_session
exit 0
fi
echo "Existing tmux sessions:"
echo ""
declare -a names
i=1
while IFS= read -r line; do
printf " %d) %s\n" "$i" "$line"
names[$i]="${line%%:*}"
((i++))
done <<< "$sessions"
echo ""
echo " n) New session"
echo " q) Quit"
echo ""
read -rp "Choice: " choice
case "$choice" in
q|Q) exit 0 ;;
n|N) new_session ;;
*)
if [[ "$choice" =~ ^[0-9]+$ ]] && [ "$choice" -ge 1 ] && [ "$choice" -lt "$i" ]; then
attach_session "${names[$choice]}"
else
echo "Invalid choice." >&2
exit 1
fi
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment