How do I know current tmux session name, by running tmux command
Solution 1:
With tmux 1.2 (and later), you can use the -p
option of display-message
to output a message to stdout (instead of displaying it to an attached client):
tmux display-message -p '#S'
#S
is formatted as the session name (see the description of the status-left
option in the man page).
Solution 2:
I'm surprised that, after nearly 5 years, no one has pointed out that neither of these answers is adequate. While both work fine as long as the current TTY is attached to the only tmux session on the host, these answers both fall flat if:
- the current terminal session is not part of a tmux session, or
- there are multiple, attached tmux sessions
In the former case, both answers here report back the name of the attached session (regardless of whether the current tty is governed by that session). In the latter case, the result is likely indeterminate or will result in multiple answers.
The proper question should be, "What is the name of the tmux session to which my current terminal session is attached?"
For he answer to that question, execute:
for s in $(tmux list-sessions -F '#{session_name}'); do
tmux list-panes -F '#{pane_tty} #{session_name}' -t "$s"
done | grep "$(tty)" | awk '{print $2}'
This works regardless of the number of tmux sessions (attached or otherwise) and regardless of whether the current terminal session is or is not part of a tmux session.
Solution 3:
Extended/corrected tim-peoples’s answer
as per don_crissti’s comment
on Why is this grep -v
not functioning as expected?.
"$(tty)" command in tim-peoples’s answer
| grep "$(tty)" |
would not work in that context as expected. It evaluates to a string 'not a tty'.
Replacing it with a variable solves this problem.
tty=$(tty)
...
| grep "$tty" |
Also, when no tmux sessions exist, the original code would produce
"no server running on /tmp/tmux-1000/default" error message.
Add 2>/dev/null
and the code would run without printing out the error message.
Modified code reads as:
tty=$(tty)
for s in $(tmux list-sessions -F '#{session_name}' 2>/dev/null); do
tmux list-panes -F '#{pane_tty} #{session_name}' -t "$s"
done | grep "$tty" | awk '{print $2}'