echo that shell-escapes arguments [duplicate]
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.)