I often switch X servers while I'm running multiple shells and GNU screen sessions. This means that X clients that I run usually end up contacting the wrong X server and I have to spend a lot of time adjusting environment variables or restarting shells.
For example, I'm currently running 11 GNU screen sessions in my workstation, each with an average of 2 or 3 shells. If I go home and SSH into my workstation, many commands will continue to contact my workstation's X server (instead of using the SSH X forwarding tunnel or, often preferable, not contacting any X servers at all).
I decided to fix this.
First, I wrote an xload shell script that initializes X environment variables and runs a command:
#!/bin/sh
function load_env {
if test -f ~/.afc-persistent-environment/$1
then
export $1=$(cat ~/.afc-persistent-environment/$1)
else
unset $1
fi
}
load_env DISPLAY
load_env XAUTHORITY
exec "$@"
Then I added the following to my ~/.bashrc:
if ! test -d ~/.afc-persistent-environment
mkdir ~/.afc-persistent-environment
fi
function save_env {
if test "${!1}" == ""
then
rm ~/.afc-persistent-environment/$1
else
echo ${!1} >~/.afc-persistent-environment/$1
fi
}
function xsave {
save_env DISPLAY
save_env XAUTHORITY
}
function xwrap {
echo $* >> ~/.afc-xwrap
}
function load_xwraps {
for program in $(cat ~/.afc-xwrap)
do
alias $program="xload $program"
done
}
load_xwraps
With this in place, I simply:
- Run xsave when I change X server (or when I decide not to use one) from a shell to make its X configuration global for all other shells (for X clients that I launch from them)
- Run xwrap passing X clients that I'd like to wrap with xload, so that the next time I launch them, they'll use the globally-saved configuration. For instance: xwrap xterm g4 vi vim ssh xlock gaim. Note that I only need to do this once per X client (ever).
- For launching X clients from programs other than the shell (which won't see the shell's aliases), substitute “program ...” with “xload program ...”.
- Run load_xwraps to reload the list of wraps. This is only needed after I run xwrap, which happens very rarely.
Last update: 2008-11-04 (Rev 14682)


