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?


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
    echo 'Not login shell'
    # do stuff in non login shell
  • 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 '13 at 21:37
  • @NickT Simple: if [ `shopt -q login_shell && echo 'y' || :` ]; then echo "Login shell"; else echo "Not login shell"; fi – Radu Rădeanu Sep 23 '13 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 '13 at 22:59

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

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

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.

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.