问题
I want to echo a text like this:
"I'm going to bed at "$'\cc3'"$var"$'\cc'
Sometimes it happens that the $var
variable begins with a number and Bash is simply concatenating it or whatever. How could I escape the $var
so it is separated but without a space between them?
回答1:
The ANSI-C Quoting mechanism in Bash uses \cx
to generate Control-X. Your use of $'\cc3'
generates a Control-C (aka \003
or \x03
) character followed by a digit 3.
Superficially, then, you want:
var=01:15
echo "I'm going to bed at "$'\cc'"$var"$'\cc'
which surrounds the time with Control-C characters (though quite why you want that, I'm not clear). If you're after a Unicode character U+0CC3 (KANNADA VOWEL SIGN VOCALIC R — ೃ — if you've got good Unicode support), then you need Bash 4.x and $'\ucc3'
.
If you're after something else, you need to explain what you're trying to echo with the ANSI-C Quoting.
回答2:
You could try sending the control-c using the \nnn
format instead of \c
:
echo $'I\'m going to bed at \003'"$var"$'\003'
(I changed the quoting slightly just to reduce the the number of context switches used to build the string.)
Or, save the control-c character in a variable:
cc=$'\cc'
echo "I'm going to bed at $cc$var$cc"
来源:https://stackoverflow.com/questions/23037718/how-to-escape-two-bash-variables-when-echoing-them