1820592 Members
2033 Online
109626 Solutions
New Discussion юеВ

Re: Change color in PS1

 
SOLVED
Go to solution
Dan Alexander
Frequent Advisor

Change color in PS1

Anyone know how to get a PS1 prompt in color?
Example
user@host:$PWD >

Where user can be one color,
host can be another...etc...

using dtterm?
5 REPLIES 5
S.K. Chan
Honored Contributor

Re: Change color in PS1

You would insert the appropriate color-esc-sequence in your PS1 definition string to get the effect. For example let say PS1 is defined as ..

PS1="`whoami`@`hostname`:"'${PWD}'""

Depending on where you define this (.profile or .kshrc), you would vi that file and insert the escape sequence. Say you want blue for "whoami" and yellow for "hostname", the color esc code would be ..

esc&v4S for blue
esc&v3S for yellow

In vi bring your cursor in the position ready for an insert (the first ` before whoami and the third ` before hostname), enter ctrl-V then ESC which will give you ^[ and then enter &v4S and &v3S. The line should look like ..

PS1="^[&v4S`whoami`@^[&v3S`hostname`:"'${PWD}'""
Charles Slivkoff
Respected Contributor
Solution

Re: Change color in PS1

Use "tput" to extract the escape codes. "setaf" for foreground, "setab" for background. "sgr0" to clear all of these.

The ANSI color codes are numbers 0-7 for black, red, green, yellow, blue, magenta, cyan, and white respectively.

Example:

Blue on white for user name, yellow on magenta for hostname:

HOSTNAME=$(hostname)
BOW="$(tput setaf 4)$(tput setab 7)"
YOM="$(tput setaf 3)$(tput setab 5)"
NONE="$(tput sgr0)"

PS1=${BOW}${LOGNAME}${NONE}@${YOM}${HOSTNAME}${NONE}

Dan Alexander
Frequent Advisor

Re: Change color in PS1

Thanks Chuck! Worked great!
Bill Hassell
Honored Contributor

Re: Change color in PS1

To add to Chuck's reply on tput...not all terminal emulators have color capability, but most have at least inverse video (white background, black letters) and a few have half-bright, underline and even blinking enhancements (HP terminals have all of these and more). tput completely relies on $TERM being set correctly for the current terminal--see man ttytype for ideas.

Here's a common set of enhancements:

export HB=$(/usr/bin/tput dim) # dim text
export HV=$(/usr/bin/tput smso) # 1/2 bright inverse
export IV=$(/usr/bin/tput bold) # inverse
export UL=$(/usr/bin/tput smul) # underline
export BL=$(/usr/bin/tput blink) # blink
export EE=$(/usr/bin/tput sgr0) # end all enhancements

And an example PS1:

export PS1='$HB$LOGNAME $IV${PWD##${PWD%/*/*}/}$EE $ '

This produces half-bright username and inverse-video current-plus-parent directory.


Bill Hassell, sysadmin
Dan Alexander
Frequent Advisor

Re: Change color in PS1

Thanks again. I have used both examples and both are exactly what I was searching for. I have played around and got my prompt to be exactly what I wanted...