反响,壳逸出参数 [英] echo that shell-escapes arguments

查看:110
本文介绍了反响,壳逸出参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有不只是回声它的参数命令,但如果需要的话(例如,如果参数包含空格或特殊字符)?

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

我需要它在某些外壳魔法的地方,而不是在一个脚本中执行命令我呼应命令。该输出被输送到一个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()).

相反的,我当然可以端口的所有外壳神奇蟒蛇,我就不需要管任何事情。

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

推荐答案

通过庆典中,的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扩大反斜线逃避相应的参数序列(除了 \\ ç终止输出,反斜杠 \\ \\ \\ <?/ code>不会被删除,并用开始\\ 0八进制转义最多可包含四个数字),而 %q 的printf导致输出的格式对应的说法,可重复使用的外壳输入。

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.

所以,你可以做这样的事情:

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

(我加了一个新行只是所以它会在一个交互的shell pretty。)

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

这篇关于反响,壳逸出参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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