Detach all other terminals except current one from a tmux session

6,302

If I've understood your question correctly, the -d option to attach-session does what you want:

tmux -2 attach-session -d -t $WHOAMI

This attaches to the named target session and detaches all other clients.

You can do something similar after the session is attached, with detach-client's -a and -t options: name the client with -t, and add -a to detach all clients apart from the named client.

screen also has a -d option which does the same thing.

Share:
6,302

Related videos on Youtube

Admin
Author by

Admin

Updated on September 18, 2022

Comments

  • Admin
    Admin over 1 year

    Is there a way to detach all terminals from a running tmux session, except the one i'm actually using?

    It seems a little weird, but the meaning of doing this is to keep some "persistency" layer to end user remote session, while ensuring that the user is using the system on only "one shell".

    As explained here, it's easy to create sessions based on user names:

    if [[ "$TMUX" == "" ]] &&
            [[ "$SSH_CONNECTION" != "" ]]; then
        # Attempt to discover a detached session and attach
        # it, else create a new session
        WHOAMI=$(whoami)
        if tmux has-session -t $WHOAMI 2>/dev/null; then
        tmux -2 attach-session -t $WHOAMI
        else
            tmux -2 new-session -s $WHOAMI
        fi
    fi
    

    But i want also, to make sure that the last attached terminal is the only one that remains attached to the user's tmux session.

    Does it have a way to accomplished that? I also accept solutions based on screen (or other multiplexers) ;)

  • kfinity
    kfinity about 7 years
    How could i have missed that after reading the man pages? You are right, but i cant leave any traces of logged session. After detaching the other terminals, how can i force a "logout" to avoid a shell opened at a prompt?
  • Stephen Kitt
    Stephen Kitt about 7 years
    Assuming the attached sessions were attached from the .bashrc containing the snippet in your question, detaching them will continue executing .bashrc after the tmux -2 attach-session and tmux -2 new-session lines; so you can add an exit there which will exit the shell after tmux detaches. Alternatively, setting TMOUT to a positive integer will close idle shells when they time out.