When creating a new shell session, the DISPLAY variable is set accordingly (it can be :0, :1, localhost:0, etc.). If I accidentally messed up the DISPLAY variable, usually I want it reset to this default value (which changes depending on setup).

My question is, how can I programmatically (via bash script) get the DISPLAY variable as it would have been when creating a new shell?

Other questions / answers usually involving just hard coding export DISPLAY=0:0 or something similar which isn't what I want (since the correct DISPLAY variable may be different)

My naive attempts

bash -c 'echo $DISPLAY'

don't work because subshells inherit the current shell variables


You can examine /proc/${pid}/environ. That contains the process' initial environment.

Here, $$ is the pid of the running shell. Note also that the variables are nil-character delimited. The -e option to cat will cause it to print non-printable characters (like the nil character), and the sed converts the representation of the nil characters to newlines.

$ cat -e "/proc/$$/environ" | sed 's/\^@/\n/g' | grep DISPLAY

$ export DISPLAY=broken

$ cat -e "/proc/$$/environ" | sed 's/\^@/\n/g' | grep DISPLAY
  • Somehow I managed to mess up the environment enough that environ was giving the incorrect display... prolly something to do with tmux-resurrect and friends...
    – Rufus
    Jun 9 at 2:52
  • @Rufus if you started a new shell after mucking with DISPLAY the new shell would have the modified value (but the parent would have the original). Jun 9 at 2:54
  • 2
    It should not be updated: "This file contains the initial environment that was set when the currently executing program was started via execve(2)." man proc.5 - Further " If, after an execve(2), the process modifies its environment (e.g., by calling functions such as putenv(3) or modifying the environ(7) variable directly), this file will not reflect those changes."
    – ibuprofen
    Jun 9 at 2:59

One way I can get the correct DISPLAY is by querying the DISPLAY variable assigned to gnome-terminal-server with the following

cat /proc/$(pidof "gnome-terminal-server")/environ | tr '\0' '\n' | grep ^DISPLAY=

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.