5

I have some code in my .bashrc that sets the terminal window title using the currently running command and it works great in Unity, where the terminal is in a window. However, when I'm logging in with the Ctrl + Alt + F1 terminal (whatever it's called), my prompt gets filled with garbage that is various escape sequences that set the (nonexistent) window title.

How can I detect from within a bash script if I'm in one or the other?

3 Answers 3

5

If you are in a GUI terminal window, you are not in a login shell. And if you are in tty, you are sure in a login shell. To test these, you can use:

shopt -q login_shell && echo 'Login shell' || echo 'Not login shell'

or, simpler:

shopt | grep login

Example to use in an if statement:

login_shell=$(shopt | grep login | cut -f2)
if [ "$login_shell" = "on" ]; then 
    echo 'Login shell'
    # do stuff in login shell
else
    echo 'Not login shell'
    # do stuff in non login shell
fi
5
  • Briefly, how do I test that in an if statement? Running the command then if [ $? ]; then... doesn't seem to work for some reason.
    – Nick T
    Sep 23, 2013 at 21:37
  • @NickT Simple: if [ `shopt -q login_shell && echo 'y' || :` ]; then echo "Login shell"; else echo "Not login shell"; fi Sep 23, 2013 at 22:11
  • I ended up adding the caveat to lump SSH terminals in with non-login shells as PuTTY can handle the retitling just fine: if [ "$login_shell" = "off" ] || [ -n "$SSH_CLIENT" ] || [ -n "$SSH_TTY" ]; then echo "full configuration"; else echo "skip retitling"; fi
    – Nick T
    Sep 23, 2013 at 22:59
  • This is not a correct answer. Both proposed answers falsely return "Login shell" and "Login_shell on" in a GUI environment when ran inside a login shell started inside a GUI terminal window. Depending on why you want to detect this, a more robust method might be preferred. Apr 16, 2023 at 0:39
  • Upon further research, I was not able to find a single concise and reliable way to determine whether the current environment is GUI based. Calling this answer incorrect may be unfair given than there are no correct answers. I still believe that using approach alone is insufficient and that other methods should be used as well. Apr 16, 2023 at 0:50
5

Can't be much simpler than this:

echo "$TERM"

if it returns "xterm" you are in a terminal window
if it returns "linux" you are in a virtual (Ctrl-Alt-F1) terminal

2
  • You should explain how to interpret the result
    – chaskes
    Oct 29, 2013 at 1:32
  • Exact values might be dependent on setup (especially on which terminal emulator is used). Sep 7, 2016 at 11:56
1

In a terminal window in an X11 session, the DISPLAY environment variable will usually be set (except some cases where su is used); this will usually not be the case in a console.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .