0

I want to have a colored prompt in bash. Usually, I do this like this, for example:

read -p $'\033[1;32m hello world?' helloWorld

This works fine, but no variables are expanded in the prompt string. Now I want color and expanded variables, but this does not work:

read -p $'\033[1;32m hello $thisVariableIsNotExpanded ?' helloWorld

I tried just using echo -e instead of read -p, but this adds a linebreak which I do not want.

So, how can I have colors and variable expansion in a read prompt?

Aaron
  • 24,009
  • 2
  • 33
  • 57
gexicide
  • 38,535
  • 21
  • 92
  • 152

4 Answers4

3

Use double quotes so that the variable gets expanded:

read -p $'\033[1;32m hello '"$thisVariableIsNotExpanded"'?' 
#                           ^                          ^

See it in action:

$ thisVariableIsNotExpanded="gexicide"
$ read -p $'\033[1;32m hello '"$thisVariableIsNotExpanded"'?' helloWorld
 hello gexicide?
# ^
# this is green
fedorqui
  • 275,237
  • 103
  • 548
  • 598
2

The best way is to use tput exactly once to obtain the escape codes (it's a bad idea to use terminal-specific literals for the escape codes - not all terminals use the same codes). Then just use ordinary double quotes, and interpolate your variables in the usual way.

bold="`tput bold`"
fg_green="`tput setaf 2`"
sgr0="``tput sgr0``"

read -p "${bold}${green}hello $thisVariableIsExpanded ?${sgr0}' helloWorld

Beware - if you're setting a foreground colour for your text, have you thought about what the background colour might be? Green against red is hard to read, and green against green impossible...

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
1

You can use echo -n and then read:

echo -ne "\033[1;32m hello $thisVariableIsNotExpanded ?"

Or you can use a variable to build the prompt:

START=$'\033[1;32m hello '
OTHER="${START}$thisVariableIsNotExpanded ?"
Stefano d'Antonio
  • 5,874
  • 3
  • 32
  • 45
0

I'm not sure this is the best solution, but echo -ne will interpret color codes without adding a linebreak.

Aaron
  • 24,009
  • 2
  • 33
  • 57