Background:
I have an X server running on my Windows machine, and ssh into one of my Linux systems. When I started doing this, I would get the ip address for my Windows machine, export it to the $DISPLAY variable, and run a few simple clients, xeyes, xclock, and an xterm. All this was done manually.
Slowly simplifying the process:
Once I figured out how I wanted the xclock to display, I created an alias for it. Then I put all the commands in a file, which I would run as needed. I still had to set $DISPLAY variable whenever I connected, though. Recently, I discovered that the IP address I connect from is stored as part of both the SSH_CLIENT and SSH_CONNECTION variables in bash.
The first step was to figure out how to extract that IP address and assign it to a variable. That was solved with the echo and cut commands.
ip=$(echo ${SSH_CLIENT} | cut -f1 -d' '):0
That pipes the value of $SSH_CLIENT to the cut command, extracting the first field, using a ' ' as the delimiter.
I then exported that to the $DISPLAY variable.
export $DISPLAY=$ip
I originally added that to the script I would run to start the X clients. However, I ran into a problem where the $DISPLAY variable wouldn't propagate to the parent shell. So if I wanted to run another client, I had to run the command manually again. That was solved by adding the command to the end of my .bashrc file. I then decided to add a check, in case I wasn't logging in via SSH, so that I would still get a valid value for $DISPLAY.
The end result:
host=$(echo ${SSH_CLIENT} | cut -f1 -d' ')
if [ -z $host ]; then
host=localhost
fi
disp=$host:0
export DISPLAY=$disp
Top comments (0)