Set PS1 with subcommand that prints colors
Set PS1 with subcommand that prints colors
When putting ANSI color codes in PS1
, they need to be surrounded with []
or else the prompt can get confused about where the editable part of the line starts. However, when a subcommand ($()
) prints colors, the []
escapes are always being written literally to the prompt...and with long enough commands in my history, the prompt gets confused.
PS1
[]
$()
[]
Here's an example:
ps1test()
ps1sub()
printf '[33[32m]Hello![33[0m]'
PS1='$(ps1sub) $ '
Expected:
$ ps1test
Hello! $
Actual (bash
installed by Git for Windows):
bash
$ ps1test
[]Hello![] $
How can I get my shell to interpret the []
escapes from a subcommand?
[]
tput
Cleaner yes, but too many calls to
tput
can significantly slow down the shell. At least on Windows. But anyway, the color codes in the question are only an example.– meustrus
Sep 14 '18 at 17:33
tput
3 Answers
3
Only [
s in the literal string are interpreted. [
s resulting from embedded expansions are not.
[
[
The easiest way to get around it is to have PROMPT_COMMAND
set a PS1
to a new literal value each time:
PROMPT_COMMAND
PS1
updateps1()
ps1sub()
printf '[33[32m]Hello $RANDOM![33[0m]'
PS1="$(ps1sub) \$ "
PROMPT_COMMAND='updateps1'
If you're trying to create a dynamic prompt, you're likely to have an easier time setting the PS1
value via a function invoked as PROMPT_COMMAND
, e.g.:
PS1
PROMPT_COMMAND
ps1test()
ps1sub()
printf '[33[32m]Hello![33[0m]'
PS1="$(ps1sub)"' $ ' # notice the double-quote
PROMPT_COMMAND=ps1test
This renders correctly as Hello! $
for me.
Hello! $
I use prompt.gem to render my prompt, you can take a look at how it configures PROMPT_COMMAND
for some inspiration.
PROMPT_COMMAND
This is exactly the right use case for eval
:
eval
ps1test()
ps1sub()
printf '[33[31m]Hello![33[0m]';
;
eval PS1="'$(ps1sub) $ '";
Only if the result of
ps1sub
doesn't change depending on the context.– meustrus
Sep 14 '18 at 17:35
ps1sub
In this case, it's equivalent to
PS1="$(ps1sub) $ "
but more fragile– that other guy
Sep 14 '18 at 21:29
PS1="$(ps1sub) $ "
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Rather that using raw color codes, it is much cleaner to use
tput
.– William Pursell
Sep 13 '18 at 21:47