Tip for setting $DISPLAY when connecting to a Linux machine.
Source: Dev.to
Background
I run an X server on my Windows machine and SSH into a Linux system.
Initially I manually set the DISPLAY variable to the Windows IP address and launched X clients such as xeyes, xclock, and xterm.
After creating an alias for xclock and putting the commands in a script, I still had to set DISPLAY each time I connected.
I discovered that the IP address of the client machine is stored in the SSH_CLIENT and SSH_CONNECTION environment variables. By extracting the first field of SSH_CLIENT I can obtain the IP address automatically.
Solution
- Extract the client IP address from
SSH_CLIENT. - Build a
DISPLAYvalue (:0). - Export
DISPLAYso X clients know where to render. - Add a fallback to
localhostwhen not connected via SSH. - Place the logic in
~/.bashrcso it runs for every interactive login.
Example script (to put in ~/.bashrc)
# Get the client IP from SSH_CLIENT (if present)
host=$(echo "${SSH_CLIENT}" | cut -f1 -d' ')
# If not connected via SSH, default to localhost
if [ -z "$host" ]; then
host=localhost
fi
# Build the DISPLAY variable and export it
export DISPLAY="${host}:0"
After adding this to ~/.bashrc, any new terminal session (including SSH logins) will have DISPLAY correctly set, allowing you to launch X clients without additional manual steps.