Which environment setting in the zsh shell will allow me to find whether I am in the x-server or if I am in the console? I am trying to find a way to implement having different setting in my .zshrc for whenever I am in my terminal emulator and whenever I am in my tty/console.

Basically I will have,


if(current shell session is in console)
    implement PROMPT x
    implement PROMPT Y

I think it would be more straightforward to check if the current tty is named like the local consoles:

case $(tty) in 
  (/dev/tty[1-9]) PS1='console version';; 
              (*) PS1='not console version';; 

That's just one way to check the result; you could use grep or parameter expansion, but it shows the idea.

You could additionally check $DISPLAY, but that's not a guarantee, and I can't imagine what you would be doing in a shell prompt that would require an X11 environment.

  • 1
    On NetBSD, $(tty) give me /dev/console – ctac_ Jun 24 '18 at 15:15

Thanks to @Ignacio Vazquez-Abrams and @Jeff Schaller (and other commenters below), I realized that $DISPLAY was the enviormental variable I needed. If you are in a display server the value held by $DISPLAY will be 0 will be returned (as something). Hence, the following code (should?) works--

if [[ -n $DISPLAY ]];
    PROMPT = (etc)
    PROMPT = (etc2)

Thanks to all.

  • 3
    Actually it won't necessarily be ":0", but it will be something; so the usual idiom is if [[ -n "$DISPLAY" ]]; then. (The construction [[ -n "$DISPLAY" ]] checks for a string of length greater than zero.) – AlexP Jun 24 '18 at 0:47
  • I see, thank you very much for clarifying. – user279540 Jun 24 '18 at 1:09
  • ... and is subject to a false positive , as a tty login could set it. – Jeff Schaller Jun 24 '18 at 3:23
  • it could be missing as entirely, btw, even in X session. – ILMostro_7 Jun 24 '18 at 3:27
  • Does my edit fix it?...I am interested in why it won't always work as when I had tested it in my linux machine, it had worked as anticipated...thanks~ – user279540 Jun 24 '18 at 4:05

When you work on console, you first login.
So if you look for login, you can know where you are.

You can try this :

[ "$(ps -t $(ps -o comm= -o tty= | \
awk '$1=="ps"{print $2}') | \
grep [l]ogin)" ] && \
echo "console" || echo "terminal"

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.