How to start tmux with attach if a session exists

  • If I use

    tmux attach
    

    I can attach to a running session but if there is no session running, I only get the error

    no sessions
    

    How can I automatically start a new session if there is none running? something like

    tmux attach-or-create-new-session
    
  • The answer is much simpler. Just put this in your ~/.tmux.conf file:

    # if run as "tmux attach", create a session if one does not already exist
    new-session -n $HOST
    

    If you run tmux attach and there is a session, then it will attach to that session (whether it's already attached or not). If there is not a session already then it will create one for you.

    this is a neat trick, but there is a caveat: if `tmux` is invoked without arguments, it will create a new session and then create a second session as soon it reaches this line in your `~/.tmux.conf`. You can see this issue by executing `tmux ls` after creating the **first** session. In practice, after you put this in your file, you cannot call `tmux` with no arguments anymore

    So you would have to add an alias `alias tmux="tmux attach"` to prevent this problem

    @BrunoPolaco: what is the big caveat with an extra empty tmux session running all the time (apart from that it doesn't look tidy in the task-list)?

    @rubo77 Resources. Some people have a few default tools, windows, panes, etc created when they launch `tmux`.

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM