Gilles identified your main problem, but I wanted to try explaining it differently.
Bash interprets the special prompt escapes only before expanding any variables in the prompt. This means that using \e
in a variable that is expanded from the prompt doesn't work, even though it does work directly in PS1
.
For example, this works as expected, and gives red text:
PS1='\e[1;31m this is in red '
But this doesn't, it just puts a literal \e
in the prompt:
RED='\e[1;31m'
PS1="$RED not in red "
If you want to store the color escapes in variables, you can use ANSI-C quoting ($'...'
) to put a literal escape character in the variable.
To do this, you can change your definition of GREEN
, RED
, and NONE
, so their value is the actual escape sequence.
GREEN=$'\033[1;32m'
RED=$'\033[1;31m'
NONE=$'\033[m'
If you do that, your first PS1
with the single quotes should work:
PS1='${RED}\h $(get_path) ${exitStatus}${NONE} '
However, then you will have a second problem.
Try running that, then press Up Arrow, then Home, and your cursor will not go back to the start of the line.
To fix that, change PS1
to include \[
and \]
around the color escape sequences, e.g.
PS1='\[${RED}\]\h $(get_path) $?\[${NONE}\] '
You can't use get_exit_status
properly here, since its output contains both printing (the exit code) and non-printing characters (the color codes), and there's no way to mark it correctly in the prompt. Putting \[...\]
would mark it as non-printing in full, which is not correct. You'll have to change the function so that it only prints the proper color-code, and then surround it with \[...\]
in the prompt.
\[
is\1
, and\[
is\2
. Those to corresponds to some readline'sRL_PROMPT_{START,END}_IGNORE
thing which asks it to ignore the bytes when counting the prompt length on screen. See https://lists.gnu.org/archive/html/bug-bash/2015-08/msg00027.html. – Mingye Wang Oct 27 '15 at 18:53\]
is\2
? And do you mean that's why it's needed for${exitStatus}
? My point was that${exitStatus}
does not contain non-printing characters, so bash should be able to correctly determine how many characters it moves the prompt without the\[
and\]
in\[${exitStatus}\]
. – Mikel Oct 27 '15 at 19:13\e
and\033
(and\[
/\]
,\u
, and\h
) from the prompt, it just does so before expanding the variables. SoPS1='\e[1;31m red'
works,red='\e[1;31m'; PS1='$red red'
doesn't. – ilkkachu Sep 19 '18 at 13:56