Better way to set Environment Variable inside a shell spawned by tmux

I’m working on a Tmux plugin to be installed via TPM, following this guide. My plugin requires a specific environment variable to be set for every new split or window. However, I haven’t found an option in Tmux that ensures environment variables are consistently set in each new shell session. Since this plugin is intended for distribution, modifying users’ shell configuration files to export variables isn’t an option—I need the plugin itself to handle setting the environment variable dynamically.

I attempted using tmux setenv, but realized that tmux global and session variables set this way are not automatically exported in the shell. Currently, I’m working around this by manually sending commands to each pane using Tmux hooks, like so

tmux set-hook -g 'after-new-window' "$EXPORT_SSH_AUTH_SOCK_COMMAND" \ 
"send-keys 'export var=1 && clear' C-m"

This approach works but feels a bit hacky. Any suggestions for a cleaner solution?

In Tmux, there isn’t a native way to enforce environment variables across new panes and windows directly. However, there are a few cleaner approaches you could consider:

  1. Use the update-environment Option: If your environment variable is set before launching Tmux, try adding it to Tmux’s update-environment option, which automatically imports specific environment variables into new sessions and panes.
tmux set-option -g update-environment "SSH_AUTH_SOCK var"

This approach works well if you can control the variable outside Tmux. However, it won’t dynamically set a new environment variable within a running Tmux instance.
2. Automate with Hooks and Scripts: Since you’re distributing a plugin, you might create a helper script that manages the variable setup for each pane. Use hooks to make it more modular and clean. For instance, define a hook like this:

tmux set-hook -g after-new-window 'run-shell "/path/to/your/script.sh"'
tmux set-hook -g after-split-window 'run-shell "/path/to/your/script.sh"'

Then, in script.sh, you could add the necessary exports:

#!/bin/bash
tmux send-keys "export var=1" C-m
  1. Leverage Tmux’s default-command Option: Set the default-command option to automatically load variables whenever a new pane is opened, like this:
tmux set-option -g default-command "export var=1 && $SHELL"

This method runs the specified command upon opening any new pane or window, ensuring the variable is set without needing to hard-code it in each command. This should streamline the environment setup across sessions without requiring modifications to the user’s configuration files.