Home > OS >  How to include variable in string that begins with $ for escaping
How to include variable in string that begins with $ for escaping

Time:11-29

I found for bash, using $'string' allows for escape characters. I also want to use a variable in the string like $'string ${var}'. However, the variable is not expanded and the output is string ${var}. Is there a way to use a variable in this type of string?

The reason I am using the string method with the dollar sign in front is to use the hexcode for a custom font to get a symbol. The desired goal is shown below.

sybmol='\uF107'
echo $'\uF101 ${symbol}'

CodePudding user response:

Simply

symbol='\uF107'
echo -e "\uF101 ${symbol}"

or

printf '%b\n'  "\uF101 ${symbol}"

CodePudding user response:

The interpretation of \u happens when the string is defined. You should use that quoting with the definition of symbol itself:

symbol=$'\uF107'

Then you can simply use two different kinds of quoting when specifying the argument of echo.

echo $'\uF101'"${symbol}"

The two quoted strings are implicitly concatenated into a single word by the shell.

Note that $'...' expands the escape sequence immediately, while echo itself can (via the -e option) expand similar sequences.

symbol='\uF107'
echo -e '\uF101'"$symobl"
  •  Tags:  
  • bash
  • Related