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.

  • 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 Jun 19 '17 at 5:43

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

| improve this answer | |

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

# leave this block alone

# 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.)

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.