2

I want to open a tmux session every time I login through SSH to my server. If the session exist, connect to it, if not, create and connect to it.

I think I need edit ~/.bashrc file to do this, but I dont have any idea to do an if/else statement or something in bash scripting.

How can I do so?

1
  • 1
    I use a simple function: shux() { ssh "$1" -t tmux a -d ;}... – jasonwryan Sep 14 '15 at 1:11
4

tmux by itself starts a new session, tmux attach attaches to a previous session.

tmux attach will fail if there is no previous session.

These two facts combine to give the following solution:

tmux attach || tmux

It tries tmux attach first, and if it fails, runs tmux by itself. This attaches to the previous session if there is one, and starts a new session if there isn't. So that's the first part.

For the second part, you want this code to run every time you log in via SSH. So you need to check:

  1. whether it is a login shell. This can be done using shopt -q login_shell.
  2. whether you are connected via SSH. This can be done by checking if $SSH_CLIENT is set, i.e.: [ -n "$SSH_CLIENT" ].

So you should add this to the end of your .bashrc:

if shopt -q login_shell && [ -n "$SSH_CLIENT" ]; then
    tmux attach || tmux
fi
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.