如何对现有的bash变量进行ANSI C引用?

mer*_*011 4 bash sed quoting

我看过这个问题,但它不包括我的用例.

假设我有一个foo包含四个字符文字的变量\x60.

我想对此变量的内容执行ANSI C Quoting并将其存储到另一个变量中.bar

我尝试了以下,但没有一个达到预期的效果.

bar=$'$foo'   
echo $bar     
bar=$"$foo"     
echo $bar       
Run Code Online (Sandbox Code Playgroud)

输出:

$foo
\x61
Run Code Online (Sandbox Code Playgroud)

期望的输出(实际值\x61):

a
Run Code Online (Sandbox Code Playgroud)

如何在一般情况下实现此目的,包括不可打印的字符?请注意,在这种情况下a,仅用作示例,以便更容易测试方法是否有效.

ric*_*ici 5

到目前为止,最简单的解决方案,如果您正在使用bash:

printf %b "$foo"
Run Code Online (Sandbox Code Playgroud)

或者,将其保存在另一个变量名称中bar:

printf -v bar %b "$foo"
Run Code Online (Sandbox Code Playgroud)

来自help printf:

除了printf(1)和printf(3)中描述的标准格式规范外,printf还解释:

 %b        expand backslash escape sequences in the corresponding argument
 %q        quote the argument in a way that can be reused as shell input
 %(fmt)T output the date-time string resulting from using FMT as a format
         string for strftime(3)
Run Code Online (Sandbox Code Playgroud)

但是有边缘情况:

\ c终止输出,\',\"和\?中的反斜杠不会被删除,以\ 0开头的八进制转义可能包含最多四位数字