help-bash
[Top][All Lists]
Advanced

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

Re: Customize bash prompt


From: Greg Wooledge
Subject: Re: Customize bash prompt
Date: Mon, 23 May 2022 09:54:33 -0400

On Mon, May 23, 2022 at 02:25:44PM +0300, Yigit Akoymak wrote:
> however I can't understand how I can
> change color of the bash prompt for exmaple I want $ sign to be green ,other
> text to red and background to blue.

Some of this is controlled by bash, but some is controlled by your
terminal.  Let's assume that the "blue background" bit is done at the
terminal level, by telling your terminal emulator to run with a blue
background.

Setting the foreground color is typically done at the application level,
which in this case is bash, running inside your terminal.  We can tell
bash to issue some commands to learn the terminal's control sequences
for setting the text foreground color, and then we can incorporate those
sequences into the shell prompt.

To do what you requested, you need three terminal sequences: one for
green text, one for red text, and one for "back to normal".  We're
going to use the tput command to get these sequences, and we're going
to store them in variables.

Then we're going to use those variables inside the PS1 variable, which
defines bash's prompt.  The most important thing here is that all of
the terminal sequences need to be surrounded with \[ \] characters inside
PS1, so that bash knows they're terminal sequences, and not regular text.

green=$(tput setaf 2)
red=$(tput setaf 1)
normal=$(tput sgr0)
PS1='\[$red\]\h:\w\[$green\]\$ \[$normal\]'

Test those commands, and if you like the result, you can put them into
your ~/.bashrc file.

You might be wondering why the "2" and "1" mean what they mean.  Terminals
traditionally use very primitive color controls, with RGB (red/green/blue)
guns being either on or off.  Colors are assigned in a very simple way:

color 0 = black (all guns off)
color 1 = red
color 2 = green
color 4 = blue

And combinations of those RGB guns:

color 3 = red + green = yellow
color 5 = red + blue = magenta
color 6 = green + blue = cyan
color 7 = red + green + blue = white

Since you only asked for red and green, all we needed were "1" (red)
and "2" (green).  If you remember RGB in that order, and understand
that each one corresponds to a bit in a binary number from 0 to 7,
you can re-derive the colors at any time.



reply via email to

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