bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: PS1 multiline with colors


From: Greg Wooledge
Subject: Re: PS1 multiline with colors
Date: Fri, 5 Jul 2013 08:14:58 -0400
User-agent: Mutt/1.4.2.3i

On Fri, Jul 05, 2013 at 12:50:53AM +0800, Chris Down wrote:
> >         PS1='\h Hello everybody\n\e[1;35m\]Hi\e[0m\]>'

> You need to properly indicate that the control codes are zero-width
> (by using \[ and \]). Without them, this is expected behaviour.
> 
> Better, don't hardcode the escape codes for colours -- it is a naive
> assumption to believe that all terminals will do what you expect. Use
> `tput' instead.

There are two ways of doing this (nobody can agree which way is better).

The first way is to put each tput result in a variable, and use the
variables inside PS1 so that they are expanded when PS1 is evaluated:

red=$(tput setaf 1)
normal=$(tput sgr0)
PS1='\h Hello everybody\n\[$red\]Hi\[$normal\]> '
export red normal PS1

The second way is to expand the variables at the time PS1 is created:

red=$(tput setaf 1)
normal=$(tput sgr0)
PS1='\h Hello everybody\n\['"$red"'\]Hi\['"$normal"'\]> '
export PS1

I prefer the first one myself, but there is no consensus.  I find the
first one more readable, both in the code where you define the prompt,
and in the result of echo "$PS1" should you ever want to SEE the prompt
and understand what it is doing.  Others prefer the second because they
don't want to lug around all the $red $normal $green $blue etc. variables.

See also http://mywiki.wooledge.org/BashFAQ/053



reply via email to

[Prev in Thread] Current Thread [Next in Thread]