简体   繁体   English

如何“释放” bash的`printf“%q”的输出

[英]How to “unescape” the output of bash's `printf “%q”`

In bash, you can use printf "%q" to escape the special characters in a string. 在bash中,可以使用printf "%q"来转义字符串中的特殊字符。 I've added a line break in the following examples for clarity's sake: 为了清楚起见,我在以下示例中添加了换行符:

$ printf "%q\n" "foo"
foo
$ printf "%q\n" 'foo$bar'
foo\$bar
$ printf "%q\n" "foo    bar"  # Tab entered with Ctrl+V Tab
$'foo\tbar'

You can supply the -v option to printf to stick the output into a variable, rather than echoing to stdout. 您可以为printf提供-v选项,以将输出粘贴到变量中,而不是回显到stdout。

Now what if I want to echo the original, unescaped string back to stdout? 现在,如果我想将原始的,未转义的字符串回显到stdout怎么办? If I just do a simple echo , it includes all the meta/control characters; 如果我只是做一个简单的echo ,它包含所有meta / control字符; echo -e gets me slightly further, but not to a fully unescaped state. echo -e使我稍微走了一点,但还没有进入完全未逃脱的状态。

Use printf and eval to "unescape" the string (it is perfectly safe, since it is quoted by bash already). 使用printfeval “取消转义”字符串(这是非常安全的,因为bash已经将其引用了)。 echo is, in general, dangerous with arbitrary user input. 通常,在任意用户输入下, echo都是危险的。

eval printf '%s\\n' "$var"

The argument to printf is %s\\\\n with double backslashes even within the single quotes, since eval will take it as one argument and then strip it (evaluate it) as is, so it effectively becomes something like: printf %s\\\\n $'12\\n34 56' which is a perfectly safe and valid command (the variable even includes a newline and space, as you can see). printf的参数是%s\\\\n ,即使在单引号中也带有双反斜杠,因为eval会将其作为一个参数,然后按原样剥离(评估)它,因此它实际上变为: printf %s\\\\n $'12\\n34 56'这是一个非常安全有效的命令(如您所见,该变量甚至包含换行符和空格)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM