If named tmux session exists, make new session and group with it, else create that named tmux session
I found a way to kinda-but-not-really do what I wanted and have used that pretty much since posting this. However, I recently stumped across an apparently completely undocumented feature that makes exactly what I want possible:
function smartgrpsc {
GRPSC_GID=${1:=grpsc}
GRPSC_CID=${GRPSC_GID}-$(date +'%H%M%S')
if ! tmux has-session -t ${GRPSC_GID} &>/dev/null; then
tmux new-session -d -s ${GRPSC_GID}
fi
tmux new-session -d -t ${GRPSC_GID} -s $GRPSC_CID \; set-option destroy-unattached \; attach-session -t $GRPSC_CID
}
if ! [[ -n "${TMUX}" || "${TERM}" =~ "tmux.*" || "${TERM}" =~ "screen.*" ]]; then
# we are (probably) not in a tmux session
smartgrpsc
sleep 5
exit
fi
The secret sauce is the \;
s (escaped semicolons) which causes new-session
to pass what follows as a tmux command to the tmux session being created. This solves the chicken-or-the-egg problem I was facing before. It allows me to create a session, change it's settings, and then attach to it by send commands to a new tmux session from the same script that started the session (and thus is running outside the session). This instead of trying to figure out what session I'm inside of after the session starts which doesn't seem to be doable from inside the .tmux.conf
.
By placing the above at the top of my .zshrc
(or .bashrc
, etc):
- it will make several checks to see if it is inside a tmux session
- if not, it runs the
smartgrpsc
function- generates a session groupname (default in the above case)
- generates a session name from the groupname and the current time of day (to prevent session id collisions).
- checks if a session beginning with or equaling the group name exists. (This is a unique handling of the session name specific to
has-session
. Sessions belonging to the group usually begin with the group name. Also poorly documented.)
- If not, it creates a new named and detached tmux session (using the group name).
- else nothing
- finally, simultaneously:
- creates another new, detached session in the same group
- sets that session to self destruct when no more clients are attached
- attaches to the newly created session.
- else nothing
The end effect is exactly as I stated in my question above. A detached, running "true" session, and a new "viewer" session for every login that is grouped with that "true" session and can see what it sees... but can also change which window it is viewing without affecting other logins. And when a login logs out that "viewer" session is cleaned up while the "true" session and all other "viewer" sessions continue.