Unix / Linux: Display Read Prompt in ANSI Color

Objective: The read shell command is used to read a line from standard input with an optional prompt. How to specify ANSI color sequences for the prompt?

The following syntax can be used to display a prompt using the read command.

To print text using ANSI escape sequences, we can use the following syntax. It will print the text “fooprompt” in bold red.

Now, the read command will not process escape sequences in the argument to -p like what the echo command does. So, to print the read prompt using ANSI color, we have to use the following syntax.

What we are doing is to define a variable called ANSIPROMPT and set it to the prompt we want together with the desired ANSI escape sequences. We then use the echo command to print the prompt with ANSI escape sequences and pass the output to the read command using command substitution.

If you are on bash shell, there is an alternative method – bash quoting. With quoting, words of the form $'string' are treated specially and to define escape characters, we can use either '\e' or '\E' escape characters.

To define the same bold red text prompt using bash shell quoting, we can use the following syntax.

ibrahim = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, php, python, java, javascript, nodejs, react); plays_on(xbox, ps4); linux_desktop_user(true); }