bash 回应 shell 转义参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2731883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
echo that shell-escapes arguments
提问by panzi
Is there a command that not just echos it's argument but also escapes them if needed (e.g. if a argument contains white space or a special character)?
是否有一个命令不仅可以回显它的参数,还可以在需要时对它们进行转义(例如,如果参数包含空格或特殊字符)?
I'd need it in some shell magic where instead of executing a command in one script I echo the command. This output gets piped to a python script that finally executes the commands in a more efficient manner (it loads the main() method of the actual target python script and executes it with the given arguments and an additional parameter by witch calculated data is cached between runs of main()).
我需要在一些 shell 魔术中使用它,而不是在一个脚本中执行命令,而是回显命令。此输出通过管道传输到最终以更有效的方式执行命令的 Python 脚本(它加载实际目标 Python 脚本的 main() 方法,并使用给定的参数执行它,计算数据的附加参数缓存在两者之间) main()) 的运行。
Instead of that I could of course port all the shell magic to python where I wouldn't need to pipe anything.
取而代之的是,我当然可以将所有 shell 魔法移植到 python 中,在那里我不需要管道任何东西。
回答by Cascabel
With bash, the printfbuiltin has an additional format specifier %q, which prints the corresponding argument in a friendly way:
使用 bash,printf内置有一个额外的格式说明符%q,它以友好的方式打印相应的参数:
In addition to the standard printf(1) formats,
%bcauses printf to expand backslash escape sequences in the corresponding argument (except that\cterminates output, backslashes in\',\", and\?are not removed, and octal escapes beginning with\0may contain up to four digits), and%qcauses printf to output the corresponding argument in a format that can be reused as shell input.
除了标准printf(1)格式,
%b导致printf的扩大在相应参数反斜杠转义序列(除了\c终止输出,反斜杠\',\"和\?不会被删除,和八进制逃逸开头\0可以含有至多四个数字),并%q导致 printf 以可重复用作 shell 输入的格式输出相应的参数。
So you can do something like this:
所以你可以做这样的事情:
printf %q "$VARIABLE"
printf %q "$(my_command)"
to get the contents of a variable or a command's output in a format which is safe to pass in as input again (i.e. spaces escaped). For example:
以可以安全地再次作为输入传入的格式(即转义空格)获取变量的内容或命令的输出。例如:
$ printf "%q\n" "foo bar"
foo\ bar
(I added a newline just so it'll be pretty in an interactive shell.)
(我添加了一个换行符,所以它在交互式 shell 中会很漂亮。)

