Ubuntu – Change colour of a specific letter in the username in bash’s PS1

bashbashrccommand lineps1

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.

Best Answer

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} "
Related Question