GibboK
GibboK

Reputation: 73988

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.

Upvotes: 2

Views: 6526

Answers (3)

Thomas Freedman
Thomas Freedman

Reputation: 43

I use this in my ~/.bashrc so if no sessions exist, start them & detach from all but ipfs session.

IPFS_SESSION=$(tmux attach-session -t ipfs 2>&1)
if [ "$IPFS_SESSION" == "sessions should be nested *" ]; then
  unset TMUX
else
  if ! tmux has-session -t sql;  then tmux new-session -d -s sql;  fi
  if ! tmux has-session -t tmp;  then tmux new-session -d -s tmp;  fi
  if ! tmux has-session -t ytdl; then tmux new-session -d -s ytdl; fi
  if ! tmux has-session -t ipfs; then tmux new-session -s ipfs; fi
fi

Upvotes: 1

spider
spider

Reputation: 89

You can use $TMUX to detect if already attached, my code is:

if [ ! "$TMUX" ]; then
        tmux attach -t main || tmux new -s main
fi

Upvotes: 7

jeremysprofile
jeremysprofile

Reputation: 11484

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.

Upvotes: 3

Related Questions