Ubuntu – How to detect if I’m in a ‘full screen’ bash shell or GUI terminal window

bashcommand line

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?

Best Answer

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