How to use printf "%q " in bash? -
i print out augments of function file. told command printf "%q ", instruction following,
# man printf %q argument printed in format can reused shell input, escaping non-print‐ able characters proposed posix $'' syntax.
on basis of instruction above, tried following code.
#!/bin/bash # file name : print_out_function_augs.sh output_file='output.txt' function print_augs() { printf "%q " "$@" >> "${output_file}" echo >> "${output_file}" } print_augs 'b c' cat "${output_file}" rm "${output_file}"
and run
bash print_out_function_augs.sh
the results following,
a b\ c
i expected results as
a 'b c'
which original augments print_augs function.
why output , original augments different? or can print out original augments are?
thank much.
bear in mind when using %q
:
argument printed in format can reused shell input, escaping non-printable characters proposed posix $'' syntax.
emphasis mine. printf
free reformat arguments way likes as long input can reused in shell. not reason input looks way does.
in bash '
character string delimiter, how tell bash "the following string contains special characters spaces, , these special characters should not parsed bash". quotes not passed commands called. command sees this:
command: printf "%q" 'b c' received args: printf::arg0: printf printf::arg1: %q printf::arg2: printf::arg3: b c
note arg3
not have quotes surrounding it. bash not pass them on.
when printf
prints args out, it not know there quotes around b c
, not print them. know space between 'b' , 'c' special shell character, , puts \
in front escape it.
this true bash functions/commands, bear in mind same happens when call print_augs
too.
if want maintain quotes around strings, you'll need double quote them bash doesn't parse them:
function print_augs2() { echo "$@" >> "${output_file}" } print_augs2 "'b c'" # output: 'b c'
Comments
Post a Comment