This is a portion of my ~/.bashrc:
prompt(){
local EXIT="$?" # return code
PS1=""
local red="\[\033[0;31m\]" # text colour
local purple="\[\033[0;35m\]" # text colour
local normal="\[\033[0m\]" # text colour
if [ $EXIT == 0 ]; then # $EXIT colour based upon its value
local return="${normal}${?}"
else
local return="${red}${?}${normal}"
fi
PS1+="${normal}[${purple}\\D{%-l:%M%P}${normal}]${return} \\[\\e]0; \
\\u@\\h: \\w\\a\\]${debian_chroot:+($debian_chroot)}\\u@\\h:\\w\\$ "
}
export PROMPT_COMMAND=prompt
This is my prompt shell in gnome-terminal (correctly displayed):
[5:01pm]0 user@host:~$
But when I switch to tty console, after I logged in, this is displayed:
[5:05pm]0 ;user@host: ~user@host:~$
This happens with regular user, but also with root on the same notebook on the same operating system. Colours are always correctly displayed, the only problem is with the way the prompt is displayed.
Sofware versions:
Some explanation of the PS1 value:
[5:01pm] # current time
0 # return/exit code of the last command (0 can be any number;
# if return code has a non-zero value, it turns red)
PS – Currently in tty consoles, I need to source ~/.bashrc
to be able to used all of my settings. (1) Where is located the tty console’s own .bashrc? (2) Or how to set it up to use the ~/.bashrc
?
Solution of the different behaviour of prompt
As the accepted answer suggests, in PS1 variable, there was a part which should be omitted, thus I just changed the last row of the function to
PS1+="${normal}[${purple}\\D{%-l:%M%P}${normal}]${return} \
${debian_chroot:+($debian_chroot)}\\u@\\h:\\w\\$ "
Solution of the Post Scriptum (PS)
tty consoles use ~/.bashrc_profile
instead of ~/.bashrc
, because (as @chepner said in comment below) the latter is sourced by GUI terminal emulator (for it usually starts a non-login interactive shell). tty console is an interactive shell.
My solution is to add the following to ~/.bash_profile
:
. ~/.bashrc
You have \\[\\e]0; \\u@\\h: \\w\\a\\]
and \\u@\\h:\\w\\$
in PS1
.
The question is why is your terminal not showing that first set but your console is.
The answer, I believe, is that you have that first set enclosed in a \[...\]
block which indicates that it is non-printing and takes up no space (this is why you need to enclose color codes in \[...\]
to avoid the prompt being shorter than the terminal expects when the codes don't create visible characters.
This is causing gnome-terminal to discard everything (even visible characters) from the output/contents of the \[...\]
block.
The console, presumably, is simply printing visible characters (and ignoring non-printing characters). (I wonder if this causes prompt size miscalculations or not.)
The solution here is to remove that first (seemingly unintentional) set of escapes.