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?
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?
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.
$'..'
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
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 usered=$(tput setaf 1)
, etc -- but this is not really an improvement, since you would still have to hardcode the "attributes off", sincesgr0
also messes with the alternate character sets, it doesn't just turn the attributes off (unfortunately). – Mar 01 '20 at 08:06tput
is at least an improvement insofar as it still works whenTERM
specifies a terminal type with different escape sequences for the colors one wants. – Charles Duffy Mar 01 '20 at 16:04