Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: sharing environment between terminals.



On 2012-11-17 at 16:39 -0800, Ray Andrews wrote:
> Is there a way to instantly share environment variables between running 
> terminals?  I often have several open, and when I set an environment 
> variable in one, I'd like it to be available in all the others too.  
> 'export' doesn't help.

If you use tmux to act as your terminal multiplexer / keepalive, then
this seems to work.

I just wrote it; this means there are probably bugs, beyond the known
limitations.

Limitation: requires tmux 1.7 or greater; 1.6 doesn't support querying
individual environment variables.

Limitation: if you update an environment variable, it's not present in
other terminals until after the next time you press return in that
shell.

Limitation: It will invoke tmux before every prompt display, and will do
so N times, where N is 1 plus the number of variables named in the
TMUX_ZSH_SHARED tmux env variable.  Optimisation left as an exercise for
the reader.  (Probably reading the output of show-environment with no
named variables, so adds 1.6/earlier compatibility; beware that
environment values are shown raw by tmux, so embedded newlines in a
variable value will mess up your output, so it's probably only safe done
the way I did it).

----------------------------8< cut here >8------------------------------
# Needs tmux 1.7 to be able to query individual environment variables

if [[ -n $TMUX ]]; then
  typeset -A latest_seen_tmuxenv
  function precmd_tmux {
    local exitstatus=$?
    local e newenv
    local -a shared overriden
    e="$(tmux show-environment TMUX_ZSH_SHARED 2>/dev/null)"
    [[ $? -ne 0 ]] && return $exitstatus
    e="${e#TMUX_ZSH_SHARED=}"
    shared=($=e)
    for e in ${shared[@]}; do
      if [[ -n "${(P)e}" && "${(P)e}" != "${latest_seen_tmuxenv[$e]}" ]]; then
        overriden+=($e)
        tmux set-environment "$e" "${(P)e}"
        latest_seen_tmuxenv[$e]="${(P)e}"
      else
        newenv="$(tmux show-environment $e 2>/dev/null)"
        if [[ $? -ne 0 ]]; then
          if [[ -n "${latest_seen_tmuxenv[$e]}" ]]; then
            unset $e
          fi
          unset latest_seen_tmuxenv[$e]
          continue
        fi
        newenv="${newenv#$e=}"
        if [[ "$newenv" != "${latest_seen_tmuxenv[$e]}" ]]; then
          latest_seen_tmuxenv[$e]="$newenv"
          typeset -g $e="$newenv"
        fi
      fi
    done
    return $exitstatus
  }

  precmd_functions+=(precmd_tmux)
fi

# tmux setenv TMUX_ZSH_SHARED "FOO BAR"
----------------------------8< cut here >8------------------------------



Messages sorted by: Reverse Date, Date, Thread, Author