I want to use tmux or screen automatically after ssh. I wrote some code in .ss/config which helps me with this.

# ~/.ssh/config

Match exec "[[ $(ps h o args p $PPID | wc -w) -eq 2 ]]"
     RemoteCommand SESSION_NAME="debek"; tmux a -t ${SESSION_NAME} || tmux new -s ${SESSION_NAME} || screen -r ${SESSION_NAME} || screen -S ${SESSION_NAME}
     RequestTTY yes

For now, there is one problem. If I want to connect to the same server from a second terminal on my local computer this obviously attach me to the same session name "debek". I can do SCREEN_NAME="debek-{RANDOM}" for a unique session name to work around this but when I, for example, lost my connection and try to connect again it will create me a new session name instead connect to my last one automatically.

Have you got any idea how to resolve this problem?

1 Answer 1


There are a few things you could do:

  1. Instead of using .ssh/config, create an alias which sshs and attaches to tmux. Then you can choose whether to attach or not from each terminal when you ssh.

  2. Create two aliases for the hostname (in /etc/hosts or DNS) and configure .ssh/config to only run tmux if you connect to one but not the other.

  3. Make the remote command only attach to tmux if it is not already attached, for example by checking tmux has 2>/dev/null && [ $(tmux lsc -t$SESSION_NAME|wc -l) -eq 0 ]. Or tmux display -pt$SESSION_NAME '#{session_attached}'.

You must log in to answer this question.

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