bashprintfescapingparameter-passing

How do I use the printf command with a format string beginning with "-"?


I have some items:

items=(one two three)

And I want to print them with leading -, to give this output:

- one
- two
- three

The obvious format string fails:

printf '- %s\n' "${items[@]}"
bash: printf: - : invalid option
printf: usage: printf [-v var] format [arguments]

I tried using \- in the format string, but that results in literal \- in the output.

If I could assume ASCII, I might get away with \055, but is there a portable way to write this?


Solution

  • In most GNU tools just use -- to notify that none of the following parameters are program arguments

    $ printf -- '- %s\n' "${items[@]}"
    - one
    - two
    - three
    

    or escape the - character code

    $ printf '\055 %s\n' "${items[@]}"
    $ printf '\x2D %s\n' "${items[@]}"