true colors in bash prompt?

4

Is it possible to use true colors in bash prompt? I'm using iTerm2 on MacOS, which does support true colors. But not sure how I use true colors for my bash prompt.

At the moment I'm using tput af <number> in my bash prompt to get colors.

ronakg

Posted 2017-06-19T03:51:59.277

Reputation: 337

It may depend on what terminals iTerm2 claims to emulate, and whether those terminals could handle 24-bit color. It may also depend on what the termcap or terminfo database says for those terminals. – Spiff – 2017-06-19T05:43:22.797

Answers

1

This appears to be possible. eg:

export PS1="\[$(printf "\x1b[48;2;15;100;50m\]A nice dark green [rgb(15,100,50)]:\[\x1b[0m")\] "

export PS1="\[$(printf "\x1b[38;2;255;100;250m\]A lovely shade of pink [rgb(255,100,250)]:\[\x1b[0m")\] "

There might be a nicer way than calling out to $(printf ...). I hope that there is, but I don't know it. The key is to wrap all the 'meta' stuff (but not the actual content) in \[ and \] to keep the shell from counting it as part of the prompt length so that it plays nicely when being redrawn (eg. when cycling through history.)

The last three numbers in each \x1b[...m expression represent the desired red, green and blue values (from 0 to 255).

The first number sets background (48) or foreground (38). I don't know what the other number does, but playing around with it adding in an additional \x1b[38;4m seems to set the text to underlined.

You might be able to glean more from this gist: https://gist.github.com/XVilka/8346728

Peter Westmacott

Posted 2017-06-19T03:51:59.277

Reputation: 111

0

So, I monkeyed around with this today for a while and got something easy to configure. I created a .bash_colors file, put this in it, and sourced it from my .bash_aliases:

# set your RGB colors
cname='108;159;164'
cdir='108;188;150'

# leave this block alone
code_color_name="\x1b[38;2;${cname}m"
code_color_dir="\x1b[38;2;${cdir}m"
code_color_reset='\x1b[0m'

# leave this block alone
c_name=$(printf "${code_color_name}")
c_dir=$(printf "${code_color_dir}")
c_rst=$(printf "${code_color_reset}")

# your PS1 prompt.  configure as desired
export PS1='\[${c_name}\]\u@\h\[${c_rst}\]:\[${c_dir}\]\w\[${c_rst}\]\$ '

I'm sure it could be done in fewer lines, but I did it the way I did for readability purposes. Just set your RGB codes and modify PS1 as you want.

(Scrolling up and down through history works cleanly, too.)

async_fm

Posted 2017-06-19T03:51:59.277

Reputation: 1