I currently have my new Konsole instances pop up already within a tmux session, whether new or attached, since tmux is awesome and you should always be inside tmux, right?

However, this puts me in a bind if I'd like to connect to a remotely managed tmux session. At present, I'm forced to plan before opening a new Konsole window that this window should not be managed by local tmux, and rather open a plain bash prompt from which I can "ssh host_foo -e tmux attach".

Ideally, I'd like to be able to detach the current tmux client process, and automatically continue to the ssh and remote tmux invocation, which would be based on whatever command was issued from within the session. I expect the interaction to work as follows:

[me@local] ~ $ tmux attach
 .... pop into local tmux session ....
[me@local] ~/tmuxdir $ ls
 tmuxfile1 tmuxfile2
[me@local] ~/tmuxdir $ detach-and-ssh foo
 .... pops out of local tmux session ....
 .... and into remote tmux session on host foo ....
[me@foo] ~ $ ls 
 remotefile1 remotefile2
[me@foo] ~ $ tmux detach
 .... pops out of remote tmux session ....
 .... and back into local tmux session ....
[me@local] ~/tmuxdir $ 

I have a feeling that this could be achieved by writing a wrapper script to call "tmux attach" in the first place, which would look for a command to call upon detach. This could be written to a file by the detach-and-ssh script. Finally, after the external part of detach-and-ssh (which is just ssh) is completed, the script loops back around to tmux attach again.

As long as only a single detach command is run at a time, a single post-detach command would suffice. However, it would be better to ensure the post-detach script would be limited to this tmux client only. If the session/client had some knowledge of the specific wrapper PID, possibly via environment variables or some other tmux variable, the post-detach command could be written to a PID-specific file.

Has anyone tried anything like this, and if so, what were the lessons learned?

Note: please do not suggest running all remote connection windows under my local tmux. The local tmux is on a laptop that hibernates and all of my running remote sessions will be lost at that point. The remote sessions really do need to be managed by a remote tmux.


1 Answer 1


Alternatively, you could nest your tmux sessions. Just create a new screen in your local tmux, ssh to your remote foo and attach to the remote tmux session. Detaching or killing your local session will not kill the remote one.

Note: To send tmux commands to the nested session, hit Ctrl+B twice (or n times, if you have n nested sessions).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .