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.
1 2 |
$ read -p "fooprompt: " fooprompt: |
To print text using ANSI escape sequences, we can use the following syntax. It will print the text “fooprompt” in bold red.
1 2 |
$ echo -e "\033[1;31mfooprompt:\033[0m" fooprompt: |
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.
1 2 3 |
$ ANSIPROMPT="\033[1;31mfooprompt:\033[0m " $ read -p $(echo -e "$ANSIPROMPT") fooprompt: |
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.
1 2 |
$ read -p $'\e[1;31mfooprompt:\e[0m ' fooprompt: |