Search code examples
bashtmux

How to detect if tmux is attached to a session in bash?


I have a .sh file which create a new session for tmux and add some windows, the file should be used only when no session exist. For instance:

tmux new-session -A -s `ax` -n ui -d
# add windows and other magic here...

I want prevent creating a session with the same name and recreating the windows in case the .sh file is accidentally re executed and the session is running.

Basically what I need is:

If a tmux session ax does not exist with that session name, create that session. If I am not attached to a tmux session, attach to that session.

I would like to know how to detect if a tmux session exist and if tmux is attached to it, in this example ax is running and preventing the execution of the .sh script or if the session does not exit I want to re-execute the .sh script.

Currently I was thinking to use:

tmux ls | grep attached

I would like to know if you know a better way.


Solution

  • It's a little hard to understand what you mean. I'm interpreting it as

    if a tmux session does not exist with that session name, create it. If I am not attached to a tmux session, attach to that session name.

    If this is wrong, please comment.

    I have similar functionality in my scripts. All I do is

    tmuxstart() {
        tmux ls | grep "sess" && { tmux a -t sess; return 0; }
        #rest of tmux script to create session named "sess"
        tmux a -t sess
    }
    

    If the session named "sess" exists, then I execute the next 2 grouped commands on the line (attach to it and exit the function).

    Note that I do not have to check if I'm already attached to the function. tmux does this automatically. If you try to attach to a tmux session while in a session, it will respond

    sessions should be nested with care, unset $TMUX to force
    

    and not recursively attach. Tmux is smart enough to keep us from shooting ourselves in the foot.