1

How can I use read command to be able to use colors in part of the text and variable in it without using --dialog command in linux shell script?

Example I need a question to appear like this in bash script:

Is this version ok?: 1.0.1 (number is in green color)

My try so far:

Version=1.0.1
textGreen='\e[1;92m' # Green
noColor='\033[0m' # No color
read -p "Is this version ok?: ${textGreen} ${Version} ${noColor} (y/n)" -n 1 -r
if [[ $REPLY =~ ^[Yy]$ ]]
then
...

This does not work it shows variable and not the number and no color at all. Thank you.

1

Your color codes are alright, I'm just not sure whether read supports colored output.

I split your read in two commands, one to print the question and one to receive the answer:

Version=1.0.1
textGreen='\e[92m'
noColor='\e[0m'
echo -e "Is this version ok?: ${textGreen}${Version}${noColor} (y/n)"
stty raw
REPLY=$(dd bs=1 count=1 2> /dev/null)
stty -raw
if [[ $REPLY =~ ^[Yy]$ ]]
then
...

echo supports colored output with the -e option. I'm now using a little hack to catch one character of raw input from the terminal prompt.

3
  • It is not working actually - color is ok but the answer will not get it... When I press Y or y it does not proceed
    – Byakugan
    Mar 1 '16 at 15:59
  • I changed the code to read just one character, instead of a whole line.
    – Kev
    Mar 1 '16 at 17:57
  • Why change the read call to something so complex? The problem isn't with the read call. Mar 2 '16 at 1:02
3

You're telling read to display a prompt that contains backslash e bracket etc. so it displays a prompt that contains backslash e bracket etc. Pass it a prompt string that contains actual escape characters. The easiest way to do that is with dollar-quote quoting.

textGreen=$'\e[1;92m' # Green
noColor=$'\033[0m' # No color
4
  • This way will still not work the variable ... - variable will not display number but the name of the variable.
    – Byakugan
    Mar 2 '16 at 1:08
  • @Byakugan It does work, unless you've changed something else. Keep the line that calls read the way it is in the question. Mar 2 '16 at 1:16
  • Will this work in echo -e "${textGreen}Text" with these escape characters?
    – Byakugan
    Mar 2 '16 at 1:40
  • @Byakugan Yes, but you don't need the -e. Both echo -e and $'…' convert backslash escapes to control characters. The advantage of $'…' is that it lets you use the string for anything, whereas echo -e only prints the result. Mar 2 '16 at 1:49

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.