回应 shell 转义参数 [英] echo that shell-escapes arguments

查看:21
本文介绍了回应 shell 转义参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个命令不仅可以回显它的参数,还可以在需要时对它们进行转义(例如,如果参数包含空格或特殊字符)?

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)?

我需要在某些 shell 魔术中使用它,而不是在一个脚本中执行命令,而是回显命令.此输出通过管道传输到最终以更有效的方式执行命令的 Python 脚本(它加载实际目标 Python 脚本的 main() 方法,并使用给定的参数执行它,计算数据的附加参数缓存在两者之间)运行 main()).

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,在那里我不需要管道任何东西.

Instead of that I could of course port all the shell magic to python where I wouldn't need to pipe anything.

推荐答案

在 bash 中,printf 内置有一个额外的格式说明符 %q,它打印相应的参数以友好的方式:

With bash, the printf builtin has an additional format specifier %q, which prints the corresponding argument in a friendly way:

除了标准的 printf(1) 格式之外,%b 使 printf 在相应的参数中展开反斜杠转义序列(除了 \c 终止输出,反斜杠在 \' 中,\"\? 没有被删除,并且以 \0 开头的八进制转义可能最多包含四位数字),并且 %q 使 printf 以可重复用作 shell 输入的格式输出相应的参数.

In addition to the standard printf(1) formats, %b causes printf to expand backslash escape sequences in the corresponding argument (except that \c terminates output, backslashes in \', \", and \? are not removed, and octal escapes beginning with \0 may contain up to four digits), and %q causes printf to output the corresponding argument in a format that can be reused as shell input.

所以你可以这样做:

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

(我添加了一个换行符,所以它在交互式 shell 中会很漂亮.)

(I added a newline just so it'll be pretty in an interactive shell.)

这篇关于回应 shell 转义参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆