9

I want to change the colour of a specific letter in my username being displayed by PS1 in bash.

Eg: If my \u is rahul, I would like the letter h to be in blue colour and rest to be white.

I do know that \u refers to username and adding a colour to an entire 'entity' is done by adding tags like: [\033[38;5;15m\].

If it's possible, can I please know how to do the same.

1 Answer 1

13

If you do not mind not using the \u escape, you could do it like this:

PS1="\[\e[0;31m\]${USER:0:1}\[\e[m\]${USER:1} "

This will set the prompt to just the username and a space. The first character of the username will be red. This works by expanding the $USER variable twice with a specific range. The first time the range is just from 0 to 1. The second time it is from 1 (the second character) to the end.

To get the prompt like you requested use this:

PS1="${USER:0:2}\[\e[0;34m\]${USER:2:1}\[\e[m\]${USER:3} "
6
  • 1
    You can just omit length to print the whole string beginning with offset: ${USER:1} for the whole username except the first character. Nice solution! Can you also show how to change the third character's color, as OP requested?
    – dessert
    Mar 14, 2018 at 13:05
  • 1
    One can test things like that with echo -e, e.g. echo -e "${USER:0:2}\e[0;34m${USER:2:1}\e[m${USER:3} "
    – dessert
    Mar 14, 2018 at 13:09
  • 2
    Does this have to work with various different usernames (e.g. highlight the 3rd letter for everyone)? If it's just for you, a simpler approach is just to hardcode the letters of your username, e.g. ra instead of ${USER:0:2}, etc.
    – egmont
    Mar 14, 2018 at 20:51
  • @egmont hardcoding is almost never the best way, but admittedly much simpler often. This way you can drop the code in a global config file or share it with others. And it handles the case when your account is renamed. Mar 14, 2018 at 20:55
  • 1
    Personally I share my own shell config between three differently named accounts. But maybe we should not get into philosophy here :) Mar 14, 2018 at 21:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .