Tip for setting $DISPLAY when connecting to a Linux machine.

Published: (January 30, 2026 at 05:40 PM EST)
2 min read
Source: Dev.to

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

  1. Extract the client IP address from SSH_CLIENT.
  2. Build a DISPLAY value (:0).
  3. Export DISPLAY so X clients know where to render.
  4. Add a fallback to localhost when not connected via SSH.
  5. Place the logic in ~/.bashrc so 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.

Back to Blog

Related posts

Read more »

Basics & History of Linux

UNIX Origins - 1964 – Bell Laboratories New Jersey began the UNIX project. - 1969 – The original project was withdrawn, but Dennis Ritchie and Ken Thompson con...