views:

65

answers:

1

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.

+8  A: 

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

Jefromi
Thanks, I did not know about that. If you use zsh, you can also use the `q` modifier: `${(q)VAR}` escapes variable in a similar way.
ZyX
Thanks, but using printf I'd have to know the number of arguments in advance. Well I guess I figure something out.
panzi
Er, is there some reason you can't do something like `for arg in "$@"; do printf %q "$arg"; done`?
Jefromi
@Jefromi Doh! I didn't think of that! :)
panzi