Updating screen session environment variables to reflect new graphical login?

You cannot start a shell script from the screen session since it would inherit the old environment. You can however us a fifo to get the new environment variables into the old screen session. You can fill that fifo when you start your graphical session.

#!/bin/bash
FIFO=/tmp/your_variables
[ -e $FIFO ] && cat $FIFO > /dev/null || mkfifo $FIFO

# save number of variables that follow
NVARS=2
echo $NVARS > $FIFO
echo ENV1=sth1 > $FIFO
echo ENV2=sth2 > $FIFO

Start that script in the background on login (it will only terminate when all variables are read from it).

Now you can read from the fifo, e.g. add this function to your .bashrc

update_session() {
  FIFO=/tmp/your_variables

  NVAR=$(cat $FIFO)
  for i in $(seq $NVAR); do
    export $(cat $FIFO)
  done
  #delete the pipe, or it will not work next time 
  rm $FIFO
}

so that you can in your old screen session

update_session

You can invoke the setenv command to change environment variables in the screen process interactively, by using: Ctrl-A+:setenv (Note the : character to enter a screen command.) You will be prompted for the environment variable name and value.

Note that (as per other answers/comments) this affects the (parent) screen process and therefore newly-created screen sessions, but not your current screen session nor any existing screen sessions.

You can specify the environment variable name and value at the same time if you want: Ctrl-A+:setenv DISPLAY :100. Will set the DISPLAY to ":100" for new screen sessions.

To remove an environment variable you can use 'unsetenv' - e.g. Ctrl-A+:unsetenv DISPLAY


I have implemented a script to do this. You can get it here: https://github.com/DarwinAwardWinner/screen-sendenv

After putting screen-sendenv.py into your $PATH, you can use the following snippet in your .bashrc:

VARS_TO_UPDATE="DISPLAY DBUS_SESSION_BUS_ADDRESS SESSION_MANAGER GPG_AGENT_INFO"
screen_pushenv () {
  screen-sendenv.py -t screen $VARS_TO_UPDATE
}
tmux_pushenv () {
  screen-sendenv.py -t tmux $VARS_TO_UPDATE
}
screen_pullenv () {
  tempfile=$(mktemp -q) && {
    for var in $VARS_TO_UPDATE; do
      screen sh -c "echo export $var=\$$var >> \"$tempfile\""
    done
    . "$tempfile"
    rm -f "$tempfile"
  }
}
tmux_pullenv () {
  for var in $VARS_TO_UPDATE; do
    expr="$(tmux showenv | grep "^$var=")"
    if [ -n "$expr" ]; then
      export "$expr"
    fi
  done
}

To use it, just run screen_pushenv before you run screen -r to reattach to your screen session. Then, after attaching with screen -r, you can update the environment in your existing shells with screen_pullenv. The tmux functions accomplish the same thing for tmux, another terminal multiplexer similar to screen.