-1

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?

3

1 Answer 1

4

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[@]}"
Sign up to request clarification or add additional context in comments.

3 Comments

I don't know why I forgot --!
you can also use various other things like %c 0x2D but not as straightforward as the above solutions in this case
that has two problems - code-points aren't portable, and we'd somehow need to get the - in front of every argument. I guess we could insert it into the array expansion instead: printf '%s\n' "${items[@]/#/- }".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.