How to create new tmux session if none exists - tmux

I am trying to figure out how to attach to a tmux session if a named tmux session exists, if not I want to create a new one with the given name.
Currently, I know of a few tmux commands which can partly achieve what I am looking for, but its not clear how to combine them together to get what I am looking for:
tmux attach attaches to an automatically existing session - but errors out if no session exists
tmux new creates a new session - but it does so every time, so I can't leave it in my .tmux.conf
tmux has-session tests whether a session exists - but I don't know how to stitch it together with the other commands
Thus, I would like to create a tmux script, so that this happens automatically, instead of having to manually create it everytime I need to log into a sessions.
How can I write a automatic script so as to create a new tmux session (if a given session name doesnt exist) or attach to a session name (if it exists)?

I figured it out (and had it pointed out to me).
tmux attach || tmux new

Alternately, you can add
new-session
to your .tmux.conf - that will create a default session on server start.
Then tmux attach will either attach to the current session (running server, that is), or create a new session (start the server, read the config file, issue the new-session command) and attach to that.

As pointed out in comments from Petr Viktorin, jkoelker and pjincz, you can use the following command to attach to mySession if it exists, and to create it if it doesn't:
tmux new -A -s mySession
From man tmux:
new-session[-AdDEP] [-cstart-directory] [-Fformat] [-nwindow-name] [-ssession-name] [-tgroup-name] [-xwidth] [-yheight] [shell-command]
(alias: new)
Create a new session with name session-name.
[...]
The -A flag makes new-session behave like attach-session if session-name already exists; in this case, -D behaves like -d to attach-session.
new-session has supported -A since tmux-1.8.

Adapting Alex's suggestion to include project based configuration upon startup, I started using the following:
# ~/bin/tmux-myproject shell script
# The Project name is also used as a session name (usually shorter)
PROJECT_NAME="myproject"
PROJECT_DIR="~/myproject"
tmux has-session -t $PROJECT_NAME 2>/dev/null
if [ "$?" -eq 1 ] ; then
echo "No Session found. Creating and configuring."
pushd $PROJECT_DIR
tmux new-session -d -s $PROJECT_NAME
tmux source-file ~/bin/tmux-${PROJECT_NAME}.conf
popd
else
echo "Session found. Connecting."
fi
tmux attach-session -t $PROJECT_NAME
where tmux-myproject.conf is my startup series of tmux commands to create my windows and panes, as well as start my editors.

Although I find rampion's answer is sufficient for using 1 session, this script lets you setup multiple sessions:
SESSIONS="work play"
function has-session {
tmux has-session -t $1 2>/dev/null
}
function except
{
if [ "$?" -eq 1 ] ; then
$1
fi
}
# Configure your sessions here
function session-work
{
tmux new-session -d -s work
tmux neww -k -t work:1
}
function session-play
{
tmux new-session -d -s play
tmux neww -k -t play:1
}
#
#MAIN
for x in $SESSIONS
do
echo $x
has-session $x
except session-$x
done
NOTE:
-k --> new-window will not be created if already exists
-d --> start session or window, but don't attach to it yet
-s --> name the session
-t --> specify a target location in the form session:window.pane

I use an alias to create a new session if needed, and attach to my default session if it already exists:
alias tmuxre='tmux new-session -t default || tmux new-session -s default'
I added this to my .login on my server.
The reason I do it this way is because I don't want to attach to the same actual session, I want a new session which uses the same group of windows.
This is also similar to running screen -xRR.

For those who want to do the same thing in fish:
tmux attach -t mysesh; or tmux new -s mysesh

(edit: A solution considering named sessions is mentioned at the end of this answer)
I came across this question when I was looking for a particular use-case, but couldn't find any solutions to it, so I'll add mine here:
Upon terminal-launch tmux should:
check whether there are any unattached sessions and use the first it can find (each session will be attached only once)
if there are no unattached sessions create a new one
After reading through the tmux man-pages and looking up arrays in bash I was able to come up with the following one-liner:
tmux attach -t ${$(tmux list-sessions -F '#{session_name}' -f '#{==:#{session_attached},0}')[1]} || tmux new
Explanation:
tmux attach -t $A:
attach to session with content of variable A (in our case the return value of the list-session command + array-index call)
tmux new:
create new session
together -> tmux attach -t $A || tmux new:
if tmux attach fails, create a new session
The next part (our $A) is finding an unattached session:
A = ${$B[1]}: return the second element in the list B (first one seems to always be an empty string)
B = tmux list-sessions -F '#{session_name}' -f '#{==:#{session_attached},0}'
tmux list-sessions: list all sessions
tmux list-sessions -F '#{session_name}: -F stands for format and -F '#{session_name}' tells tmux to only show the name of the session and nothing else when it outputs the list
tmux list-sessions -f '#{==:#{session_attached},0}': -f stands for filter and -f '#{==:#{session_attached},0}'tells tmux to show only those list-elements, where the session_attached-value is equal to 0
tmux list-sessions -F '#{session_name}' -f '#{==:#{session_attached},0}': both flags in combination will output only the session name and only for those elements of the list, where the session_attached-value is equal to 0 (=unattached sessions)
Example:
My application was for WSL, so I added it to the launch of my Ubuntu profile inside the settings.json of Windows Terminal:
"commandline": "C:\\Windows\\system32\\wsl.exe -d Ubuntu-22.04 tmux attach -t ${$(tmux list-sessions -F '#{session_name}' -f '#{==:#{session_attached},0}')[1]} || tmux new",
Edit:
If you have ([a-zA-Z]) named sessions you can sort the list to put those at the beginning:
tmux attach -t ${$(sort -n <<<"${$(tmux list-sessions -F '#{session_name}' -f '#{==:#{session_attached},0}')[*]}")[1]} || tmux new
If you add tmux new -s "primary" || at the beginning of the previous command it will try to create the session with the name "primary" and if it already exists it will only attach to it if it is still unattached, otherwise it will take another unattached session (prioritizing named over unnamed) or just create a new unnamed session if there are no unattached sessions left.
Caveat: each time you run this command and "primary" already exists it will output an error-message that it wasn't able to create a session called "primary" (only visible for a split second)
edit edit:
you can redirect those messages by using &> /dev/null:
(tmux new -s primary || tmux new -s secondary || tmux new -s tertiary) &> /dev/null || tmux attach -t ${$(sort -n <<<"${$(tmux list-sessions -F '#{session_name}' -f '#{==:#{session_attached},0}')[*]}")[1]} || tmux new"

Related

tmux: How to automatically list-sessions when starting a new tmux sessions?

Sometime I do have a couple of sessions already running, I didn't name them or I use random name.
Currently I have to ctrl-a and s or :list-sessions in order to list all sessions and switch to them.
When I started a new tmux via tmux command. How can I automatically list existing sessions?
I have a shell function (for Bash) for this. When I run tmux without any options and there are already some sessions it'll prompt for me to choose one.
function _tmux()
{
if [[ $# == 0 ]] && command tmux ls >& /dev/null; then
command tmux attach \; choose-tree -s
else
command tmux "$#"
fi
}
alias tmux=_tmux

tmux: will it support regex for the session name when we want to capture pane output

I have a situation where in my script i keep appending some text to the original session name
EG: First time when i create a new session
today=`date +%Y-%m-%d-%H_%M_%S_%N`
tmux new-session -d -s "$today" zsh /home/path/to/script.sh "with_params"
IN my script.sh based on some condition i want add some text infront of the session name:
session_name=`tmux display-message -p "#S"` #this gets the session name in which the script is running
tmux rename-session -t ${session_name} ABC_${session_name}
....after some code again i rename it
session_name=`tmux display-message -p "#S"` #this gets the session name in which the script is running
tmux rename-session -t ${session_name} XYZ_${session_name}
So whats happening here is
my original session name is "2020-04-10-11_52_01_953906687"
Its gets renamed to XYZ_2020-04-10-11_52_01_953906687 or ABC_2020-04-10-11_52_01_953906687 or KLM_2020-04-10-11_52_01_953906687 etc based on certain conditions.
Now i want to capture the last five lines output of this session. I Know it has only one window and only one pane
$ tmux capture-pane -p -S- -E- -e -t *2020-04-10-11_52_01_953906687* |sed '/^$/d'|tail -5
zsh: no matches found: *2020-04-10-11_52_01_953906687*
So how can i do this.
You need to escape the *s if you want them to be processed by tmux rather than the shell. Either \* or put the whole thing in 's.

Different starting directory per window?

I daily use tmux (2.5) on my laptop to work, and my tmux sessions have a starting directory which is the working directory I started the tmux session from. Every pane/window I open start with this starting directory as working directory.
I can change this starting directory, and this change would apply to the whole session.
But if I want to work on a different project with several panes, I could start a new window, but every pane I would open in it would start with the session's starting directory : I would have to cd to the new location for each pane which isn't practical.
If I need to work on several project/directories simultaneously, I can start a new terminal session, then cd to the relevant directory/project and start a new tmux session. That's not complicated.
But if I want to do the same thing on a server through ssh, I'd need to either :
open a new ssh session.
either embed my remote tmux sessions in an other tmux session.
Neither sounds practical to me, I'd prefer a single tmux session on the remote machine.
I think it would be more convenient to being able to start new window with its own starting directory location that would apply to any new pane opened in it. Is there a way to achieve this?
Edit :
I already tried the -c parameter of tmux new-window command.
But it doesn't assign its starting directory to the window created this way, it only applies this custom starting directory to the first pane created.
Any new pane opened in this window then uses the session's starting directory as default working dir (and not the path passed to tmux new-window).
This question is very similar to: https://unix.stackexchange.com/questions/12032/create-new-window-with-current-directory-in-tmux
It depends on your tmux version but the -c parameter does do the trick but it does not remember the setting. There used to be a default-path setting but that has been removed in version 1.9 unfortunately.
For newer versions you will need to pass along the -c in all cases (you can use an alias if you manually execute that command) or if you use key bindings you need to rebind the split/new window keys.
bind '"' split-window -c "#{pane_current_path}"
bind % split-window -h -c "#{pane_current_path}"
bind c new-window -c "#{pane_current_path}"
To use a custom path instead of the current pane path, execute this command:
tmux setenv custom_path /home/whatever/some/path
Put this in your config:
bind '"' split-window -c "#{custom_path}"
bind % split-window -h -c "#{custom_path}"
bind c new-window -c "#{custom_path}"
Yes, it turns out the -c option to the new-window command is what you are looking for: https://unix.stackexchange.com/questions/12032/create-new-window-with-current-directory-in-tmux Also, this: https://unix.stackexchange.com/questions/101949/new-tmux-panes-go-to-the-same-directory-as-the-current-pane-new-tmux-windows-go
So either of tmux new-window -c $(pwd) or tmux new-window -c /path/to/dir inside your tmux session should do it.

How to auto-update SSH agent environment variables when attaching to existing tmux sessions?

I am trying to find a nice way to restore the SSH agent when I reconnect a disconnected tmux session.
The cause seems to be that the SSH agent session changes but the environment variable from the tmux session is not updated.
How can I automate this, before attaching the session itself? Because the session I am attaching to does not always have a bash prompt, so I cannot afford to type something inside it. It has to be something to run before creating or attaching the tmux session.
An example of the code I'm running is at https://gist.github.com/ssbarnea/8646491 -- a small ssh wrapper that is using tmux to create persistem ssh connections. This works quite well, but sometimes the ssh agent stops working so I am no longer able to use it to connect to other hosts.
There's an excellent gist by Martijn Vermaat, which addresses your problem in great depth, although it is intended for screen users, so I'm adjusting it for tmux here.
To summarize:
create ~/.ssh/rc if it doesn't exist yet, and add the following content:
#!/bin/bash
# Fix SSH auth socket location so agent forwarding works with tmux.
if test "$SSH_AUTH_SOCK" ; then
ln -sf $SSH_AUTH_SOCK ~/.ssh/ssh_auth_sock
fi
Make it work in tmux, add this to your ~/.tmux.conf:
# fix ssh agent when tmux is detached
setenv -g SSH_AUTH_SOCK $HOME/.ssh/ssh_auth_sock
Extra work is required if you want to enable X11 forwarding, see the gist.
While tmux updates SSH variables by default, there is no need to
change/add socket path
change the SSH_AUTH_SOCKET variable
I like the solution by Chris Down which I changed to add function
fixssh() {
eval $(tmux show-env \
|sed -n 's/^\(SSH_[^=]*\)=\(.*\)/export \1="\2"/p')
}
into ~/.bashrc. Call fixssh after attaching session or before ssh/scp/rsync.
Newer versions of tmux support -s option for show-env, so only
eval $(tmux show-env -s |grep '^SSH_')
is possible.
Here's what I use for updating SSH_AUTH_SOCK inside a tmux window (based on Hans Ginzel's script):
alias fixssh='eval $(tmux showenv -s SSH_AUTH_SOCK)'
Or for tmux that does not have showenv -s:
alias fixssh='export $(tmux showenv SSH_AUTH_SOCK)'
Here is my solution which includes both approaches, and does not require extra typing when I reconnect to tmux session
alias ssh='[ -n "$TMUX" ] && eval $(tmux showenv -s SSH_AUTH_SOCK); /usr/bin/ssh'
There are lots of good answers here. But there are cases where tmux show-environment doesn't see SSH_AUTH_SOCK. In that case you can use find to locate it explicitly.
export SSH_AUTH_SOCK=$(find /tmp -path '*/ssh-*' -name 'agent*' -uid $(id -u) 2>/dev/null | tail -n1)
That's long and complicated, so I'll break it down...
01 export SSH_AUTH_SOCK=$(
02 find /tmp \
03 -path '*/ssh-*'
04 -name 'agent*'
05 -uid $(id -u)
06 2>/dev/null
07 | tail -n1
08 )
export the SSH_AUTH_SOCK environment variable set to the output of the $() command substitution
find files starting in /tmp
limit results to only those with /ssh- in the path
limit results to only those whose name begins with agent
limit results to only those with a user id matching the current user
silence all (permissions, etc.) errors
take only the last result if there are multiple
You may be able to leave off 6 & 7 if you know that there will only be 1 result and you don't care about stderr garbage.
I use a variation of the previous answers:
eval "export $(tmux show-environment -g SSH_AUTH_SOCK)"
assuming that you did the ssh agent started from the outer environment. Same goes for other environment variables such as DISPLAY.
I prefer to avoid configuring TMUX (etc) and keep everything purely in ~/.ssh/. On the remote system:
Create ~/.ssh/rc:
#!/bin/bash
# Fix SSH auth socket location so agent forwarding works within tmux
if test "$SSH_AUTH_SOCK" ; then
ln -sf $SSH_AUTH_SOCK ~/.ssh/ssh_auth_sock
fi
Add following to ~/.ssh/config so it no longer relies on $SSH_AUTH_SOCK, which goes stale in detached terminals:
Host *
IdentityAgent ~/.ssh/ssh_auth_sock
Known limitations
ssh-add doesn't use ~/.ssh/config and so cannot communicate with ssh-agent. Commands like ssh-add -l produce errors, even though ssh user#host works fine, as does updating git remotes which are accessed via SSH.
I may have worked out a solution that is fully encapsulated in the ~/.tmux.conf configuration file. It is a different approach than modifying the ~/.bash_profile and ~/.ssh/rc.
Solution only using ~/.tmux.conf
Just cut and paste the following code into your ~/.tmux.conf
# ~/.tmux.conf
# SSH agent forwarding
#
# Ensure that SSH-Agent forwarding will work when re-attaching to the tmux
# session from a different SSH connection (after a dropped connection).
# This code will run upon tmux create, tmux attach, or config reload.
#
# If there is an SSH_AUTH_SOCK originally defined:
# 1) Remove all SSH related env var names from update-environment.
# Without this, setenv cannot override variables such as SSH_AUTH_SOCK.
# Verify update-environment with: tmux show-option -g update-environment
# 2) Force-set SSH_AUTH_SOCK to be a known location
# /tmp/ssh_auth_sock_tmux
# 3) Force-create a link of the first found ssh-agent socket at the known location
if-shell '[ -n $SSH_AUTH_SOCK ]' " \
set-option -sg update-environment \"DISPLAY WINDOWID XAUTHORITY\"; \
setenv -g SSH_AUTH_SOCK /tmp/ssh_auth_sock_tmux; \
run-shell \"ln -sf $(find /tmp/ssh-* -type s -readable | head -n 1) /tmp/ssh_auth_sock_tmux\" \
"
Caveat
The above solution along with the other solutions are susceptible to a race condition when initiating multiple connections to the same machine. Consider this:
Client 1 Connect: SSH to machineX, start/attach tmux (writes ssh_auth_sock link)
Client 2 Connect: SSH to machineX, start/attach tmux (overwrites ssh_auth_sock link)
Client 2 Disconnect: Client 1 is left with a stale ssh_auth_sock link, thus breaking ssh-agent
However, this solution is slightly more resilient because it only overwrites the ssh_auth_sock link upon tmux start/attach, instead of upon initialization of a bash shell ~/.bash_profile or ssh connection ~/.ssh/rc
To cover this last race condition, one may add a key binding to reload the tmux configuration with a (Ctrl-b r) key sequence.
# ~/.tmux.conf
# reload config file
bind r source-file ~/.tmux.conf
From within an active tmux session, executing this sequence when the ssh_auth_sock link goes stale will refresh the ssh-agent connection.
In case other fish shell users are wondering how to deal with this when using fish (as well as for my future self!). In my fish_prompt I added a call to the following function:
function _update_tmux_ssh
if set -q TMUX
eval (tmux show-environment SSH_AUTH_SOCK | sed 's/\=/ /' | sed 's/^/set /')
end
end
I suppose that more advanced *nix users would know how to replace sed with something better, but this works (tmux 3.0, fish 3.1).
Following up on #pymkin's answer above, add the following, which worked with tmux 3.2a on macOS 11.5.3:
To ~/.tmux.conf:
# first, unset update-environment[SSH_AUTH_SOCK] (idx 3), to prevent
# the client overriding the global value
set-option -g -u update-environment[3]
# And set the global value to our static symlink'd path:
set-environment -g SSH_AUTH_SOCK $HOME/.ssh/ssh_auth_sock
To ~/.ssh/rc:
#!/bin/sh
# On SSH connection, create stable auth socket path for Tmux usage
if test "$SSH_AUTH_SOCK"; then
ln -sf "$SSH_AUTH_SOCK" ~/.ssh/ssh_auth_sock
fi
What's going on? Tmux has the semi-helpful update-environment variable/feature to pick up certain environment variables when a client connects. I.e. when you do tmux new or tmux attach, it'll update the tmux environment from when you ran those commands. That's nice for new shells or commands you run inside tmux afterwards, but it doesn't help those shells you've started prior to the latest attach. To solve this, you could use some of the other answers here to have existing shells pick up this updated environment, but that's not the route I chose.
Instead, we're setting a static value for SSH_AUTH_SOCK inside tmux, which will be ~/.ssh/ssh_auth_sock. All shells inside tmux would pick that up, and never have to be updated later. Then, we configure ssh so that, upon connection, it updates that static path with a symlink to the latest real socket that ssh knows.
The missing piece from #pymkin's answer is that Tmux will have the session value override the global value, so doing set-environment -g isn't sufficient; it gets squashed whenever you re-attach. You also have to also tell tmux not to update SSH_AUTH_SOCK in the session environment, so that the global value can make it through. That's what the set-option -g -u is about.
After coming across so many suggestions, I finally figured out a solution that enables TMUX update the stale ssh agent after being attached. Basically, both the zshrc files on the local and remote machines need to be modified.
Insert the following codes into the local zshrc, which is based on this reference.
export SSH_AUTH_SOCK=~/.ssh/ssh-agent.$(hostname).sock
ssh-add -l 2>/dev/null >/dev/null
# The error of executing ssh-add command denotes a valid agent does not
# exist.
if [ $? -ge 1 ]; then
# remove the socket if it exists
if [ -S "${SSH_AUTH_SOCK}" ]; then
rm "${SSH_AUTH_SOCK}"
fi
ssh-agent -a "${SSH_AUTH_SOCK}" >/dev/null
# one week life time
ssh-add -t 1W path-to-private-rsa-file
fi
Insert the following code into the remote zshrc, where the tmux session will be attached.
alias fixssh='eval $(tmux showenv -s SSH_AUTH_SOCK)'
Then ssh into the remote machine. The -A option is necessary.
ssh -A username#hostname
Attach the TMUX session. Check the TMUX evironment variables
# run this command in the shell
tmux showenv -s
# or run this command after prefix CTRL+A or CTRL+B
:show-environment
Run fixssh in the previously existed panes to update the ssh agent. If a new pane is created, it will automatically get the new ssh-agent.
Here's another simple Bash solution, using PROMPT_COMMAND to update the SSH_* vars inside tmux before each prompt is generated. The downside to this solution is that it doesn't take effect in existing shells until a new prompt is generated, because PROMPT_COMMAND is only run before creating new prompts.
Just add this to your ~/.bashrc:
update_tmux_env () {
# Only run for shells inside a tmux session.
if [[ -n "$TMUX" ]]; then
eval $(tmux show-env -s | grep '^SSH_')
fi
}
export PROMPT_COMMAND=update_tmux_env
Here's a new fix to an old problem: I think it's simpler than the other fixes and there's no need to make a static socket or mess with the shell prompt or make a separate command you have to remember to run.
I added this code added to my .bashrc file:
if [[ -n $TMUX ]]; then
_fix_ssh_agent_in_tmux () { if [[ ! -S $SSH_AUTH_SOCK ]]; then eval export $(tmux show-env | grep SSH_AUTH_SOCK); fi }
ssh () { _fix_ssh_agent_in_tmux; command ssh $#; }
scp () { _fix_ssh_agent_in_tmux; command scp $#; }
git () { _fix_ssh_agent_in_tmux; command git $#; }
rsync () { _fix_ssh_agent_in_tmux; command rsync $#; }
fi
If the shell is running within tmux, it redefines 'ssh' and its ilk to bash functions which test and fix SSH_AUTH_SOCK before actually running the real commands.
Note that tmux show-env -g also returns a value for SSH_AUTH_SOCK but that one is stale, I assume it's from whenever the tmux server started. The command above queries the current tmux session's environment which seems to be correct.
I'm using tmux 2.6 (ships with with Ubuntu 18.04) and it seems to work well.

TMUX setting environment variables for sessions

I work in a situation where I have multiple projects and within each are many scripts that make use of environment variables set to values specific to that project.
What i'd like to do is use a separate tmux session for each project and set the variables so that they are set for all windows in that session.
I tried to use the set-environment option which works using the -g option but then sets the variable for all sessions connected to that server.
Without the -g option I see its set when using show-environment but can't access the variable in the shell.
Has anyone come up with a way of fixing this?
Using tmux 1.8 and tcsh
I figured out a way to do this. I'm using tmux 2.5.
Background
In the tmux man page, it states that there are two groups of environment variables: global and per-session. When you create a new tmux session, it will merge the two groups together and that becomes the set of environment variables available within the session. If the environment variables get added to the global group, it appears that they get shared between all open sessions. You want to add them to the per-session group.
Do this
Step 1: Create a tmux session.
tmux new-session -s one
Step 2: Add an environment variable to the per-session group.
tmux setenv FOO foo-one
This adds the environment variable to per-session set of environment variables. If you type tmux showenv, you'll see it in the output. However, it isn't in the environment of the current session. Typing echo $FOO won't give you anything. There's probably a better way to do this, but I found it easiest to just export it manually:
export FOO='foo-one'
Step 3: Create new windows/panes
Now, every time you create a new window or pane in the current session, tmux will grab the FOO environment variable from the per-session group.
Automating it
I use bash scripts to automatically create tmux sessions that make use of these environment variables. Here's an example of how I might automate the above:
#!/bin/bash
BAR='foo-one'
tmux new-session -s one \; \
setenv FOO $BAR \; \
send-keys -t 0 "export FOO="$BAR C-m \; \
split-window -v \; \
send-keys -t 0 'echo $FOO' C-m \; \
send-keys -t 1 'echo $FOO' C-m
You can access tmux (local) environment variables for each session, while in a session, with the command:
bash> tmux show-environment
If you add the -g parameter you get the environment for all sessions, i.e. the global environment. The local environments are NOT the same as the global environment. The previous command prints the entire local environment, but you can also look at just one variable:
bash> tmux show-environment variable_name
variable_name=value
To get the value, you could use some 'sed' magic or use 'export' on a single variable, or you can even 'export' the entire environment to your shell. Below are the 3 approaches.
bash> tmux show-environment variable_name | sed "s:^.*=::"
value
bash> eval "export $(tmux show-environment variable_name)"
bash> echo $variable_name
value
bash> for var in $(tmux show-environment | grep -v "^-"); do eval "export $var"; done;
bash> echo $variable_name
value
If needed, you can just add the -g parameter after the show-environment command if you want to access the global environment.
I've done a simple
export MY_VAR="some value"
before I start the tmux session, which gives me access to MY_VAR from all windows inside that session.
Version 3.2 of tmux will support a -e option for the new-session command for altering the local environment directly.
In the mean time, you can use this to run a new tmux session with a particular environment available and up to date (or one of the other solutions mentioned):
tmux new-session 'export MY_VAR=value; exec bash'
The problem with tmux is that when you first run it, the tmux server is created and it inherits the environment that is available at this time of creation. This is called the global environment. When you run tmux again and create a new session, the tmux server still holds its copy of the environment. But this copy is the "old" environment that the server learned about when it was created, i.e. the global environment.
About the tmux commands that work with the tmux environment:
set update-environment MY_VAR: this will tell tmux to take the MY_VAR variable from the global environment and make it a session environment, i.e. a local environment (listed by the show-environment command). Then, the session will be able to change the value of this variable without affecting the global environment.
set-environment MY_VAR value: This will create (or change) a variable in the local environment of the session.
set-environment -g MY_VAR value: This will create (or change) a variable in the global environment.
Also, note that when you run tmux and tmux calls bash (or another shell), bash will have a copy of the server's (global) environment. Even if you change an environment variable before calling tmux, creating a new session will be oblivious of the changes. If you add a tmux command in a conf file and run tmux e.g. with tmux source-file tmux-session.conf, any variable you mention in the conf will be evaluated in the context of the global environments the tmux server knows about and not the in the context from where you run the tmux command. So, in order to make a new session see the new value of the variable, you have to call tmux in a way that passes the new value of the env variable directly to it. This is what the solutions here try to do. This is also what the new -e option will allow you to do.
I approached this a little differently, assuming I had separate initialization scripts for each environment.
Using tmux v3.0a.
The spec:
When I invoke tmux I want it to load up a specific environment for that session.
For each window within the tmux session I want that same environment session replicated.
I also want to be able to invoke subsequent tmux sessions with different environments and each window invocation should load that environment. (just like the first session) And subsequent sessions should not interfere with prior sessions.
I have shell scripts to initialize each of my environments.
So how can I associate a shell script with a session and have all window invocations use that shell script?
Simple Solution:
Found a simple solution here: How to start two tmux sessions with different environments?
With my original solution I ran into an issue with the tmux global environment. When I ran multiple sessions, whichever one ran first set the global environment. Then I would need to close other tmux sessions before I ran new sessions.
A better solution is to set up a separate tmux server for each environment.
Use the -L flag to tmux from within a shell that already has the environment defined you want.
Shell environment A: tmux -L environA
Shell environment B: tmux -L environB
Name your environments any way you want. Set up some aliases for each environment? Or you can test environment variables to determine which tmux server you want to use. Each tmux named server will keep its environment separate.
Then there is no need to set bash startup files, etc. as I had described in my original solution.
Example
In my case I'm starting a tmux session per project within a bash script and I needed to activate a relevant virtual environment for that session, including any newly opened tabs. To do so, I added the following virtual environment activation code to the ~/.bashrc:
if [ -n "$VIRTUAL_ENV" ]; then
source $VIRTUAL_ENV/bin/activate;
fi
However if I need to set foo environment for Session_1 and bar environment for Session_2, the VIRTUAL_ENV variable is globally set to bar after creating Session_2, so any newly opened tabs in Session_1 erroneously ends up in bar environment.
Solution
original HOWTO (commit).
Add the following in your ~/.profile (or ~/.bashrc):
# For Tmux VirtualEnv support
tmux_get_var(){
local key=$1
[[ -n "$TMUX" ]] && tmux showenv | awk -F= -v key="$key" '$1==key {print $2}'
}
# activate the virtual environment if it is declared
venv=$(tmux_get_var "VIRTUAL_ENV")
if [ -n "$venv" ]; then
source $venv/bin/activate;
fi
Set the VIRTUAL_ENV variable for the target session:
tmux setenv -t ${SESSION_NAME} 'VIRTUAL_ENV' /path/to/virtualenv/
Setting it for current session is quite easy: Ctr-b: to open tmux command prompt and enter setenv FOO foo. This will not apply for existing windows -- but there you can use export $(tmux show-env FOO).
For new sessions this pattern might be useful:
tmux new -s session
Ctr-b : set-env FOO foo -- set FOO=foo for the session
Ctr-b c -- create new, second window ($FOO is set here)
Ctr-b l -- go to old, first window
exit the first window
all windows now have FOO=foo
Tested with Tmux 1.8.

Resources