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
    if tmux has-session -t $WHOAMI 2>/dev/null; then
    tmux -2 attach-session -t $WHOAMI
        tmux -2 new-session -s $WHOAMI

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) ;)

1 Answer 1


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.

  • 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?
    – user34720
    Commented Mar 2, 2017 at 12:28
  • 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. Commented Mar 2, 2017 at 12:35

You must log in to answer this question.