echo that shell-escapes arguments [duplicate]

狂风中的少年 提交于 2019-12-03 15:28:12

问题


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()).

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


回答1:


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

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

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



来源:https://stackoverflow.com/questions/2731883/echo-that-shell-escapes-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!