echo that shell-escapes arguments [duplicate]

2019-03-18 04:40发布

This question already has an answer here:

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条回答
2楼-- · 2019-03-18 05:19

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

查看更多
登录 后发表回答