3
input() {
    read -p $'\e[31m\e[1m $1 [Y/n] \e[0m' -n 1 -r
}

input "test"
exit

This just prints "$1" in as the line of text. Why isn't it printing "test" and how can I make it do so?

Charles Duffy
  • 1,732
  • 15
  • 22
Nate Houk
  • 195
  • 1
    Better to avoid using descriptors like "this" in a title, as such a title cannot convey a question's topic to someone unless they click through and read the body. Ideally, a title should be sufficient to convey to someone whether they have the same problem, and thus whether an existing question's answers are likely to help them, when they come across it in search results. – Charles Duffy Mar 01 '20 at 05:23
  • 1
  • Instead of fighting with the quotes, use some variables: red=$'\e[31m'; bold=$'\e[1m'; attroff=$'\e[m'; ...; input(){ read -p "$red$bold $1 [Y/n] $attroff" -n 1 -r; }. And instead of hard-coding colors, you can use red=$(tput setaf 1), etc -- but this is not really an improvement, since you would still have to hardcode the "attributes off", since sgr0 also messes with the alternate character sets, it doesn't just turn the attributes off (unfortunately). –  Mar 01 '20 at 08:06
  • Using tput is at least an improvement insofar as it still works when TERM specifies a terminal type with different escape sequences for the colors one wants. – Charles Duffy Mar 01 '20 at 16:04

1 Answers1

13

The problem is that variables are not expanded inside single quotes. You are looking for this:

read -p $'\e[31m\e[1m '"$1"$' [Y/n] \e[0m' -n 1 -r

See that only the escape sequences are single quoted now, while $1 is double quoted.

Quasímodo
  • 18,865
  • 4
  • 36
  • 73
  • Given that $'..' isn't even standard, it might be better to consider it a completely different form of quoting than plain single quotes '..' are. Neither of course expands parameters, but some other generalizations might not apply. – ilkkachu Mar 01 '20 at 12:41