Skip to content

Instantly share code, notes, and snippets.

@sycobuny
Created December 27, 2012 18:26
Show Gist options
  • Save sycobuny/4390647 to your computer and use it in GitHub Desktop.
Save sycobuny/4390647 to your computer and use it in GitHub Desktop.
Script for re-attaching to existing tmux sessions while maintaining window independence, à la `screen -x`
#!/bin/bash
#
# Re-modified script from
# https://mutelight.org/practical-tmux
# Which is modified from:
# http://forums.gentoo.org/viewtopic-t-836006-start-0.html
#
# chmod +x it and put it in your $PATH for easy use; I stuck it in
# ~/.tmux-attach.bash and added an alias for it, do whatever you like.
#
# Works because bash automatically trims by assigning to variables and by
# passing arguments
trim() { echo $1; }
if [[ -z "$1" ]]; then
echo "Specify session name as the first argument"
exit
fi
# Only because I often issue `ls` to this script by accident
if [[ "$1" == "ls" ]]; then
tmux ls
exit
fi
base_session="$1"
# This actually works without the trim() on all systems except OSX
tmux_nb=$(trim `tmux ls | grep "^$base_session" | wc -l`)
if [[ "$tmux_nb" == "0" ]]; then
echo "Launching tmux base session $base_session ..."
tmux new-session -s $base_session
else
# Make sure we are not already in a tmux session
if [[ -z "$TMUX" ]]; then
# Kill defunct sessions first
old_sessions=$(tmux ls 2>/dev/null | egrep "^[0-9]{14}.*[0-9]+\)$" | cut -f 1 -d:)
for old_session_id in $old_sessions; do
tmux kill-session -t $old_session_id
done
session_num=$(tmux ls | grep "^$base_session-" | cut -d- -f2 | sort -rn | head -n1)
if [[ -z "$session_num" ]]; then
session_num=0
fi
session_num=$(($session_num + 1))
echo "Launching copy of base session $base_session ..."
# Session is is date and time to prevent conflict
session_id=$base_session-$session_num
# Create a new session (without attaching it) and link to base session
# to share windows
tmux new-session -d -t $base_session -s $session_id
# Create a new window in that session
#tmux new-window
# Attach to the new session
tmux attach-session -t $session_id
# When we detach from it, kill the session
tmux kill-session -t $session_id
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment