I have the following line:

printf "---- %.55s\n" "$1 --------------"

When I run this under bash I get the following error:

printf: --: invalid option printf: usage: printf [-v var] format [arguments]

This is because (I think) printf interprets the string "----" as the beginning of an argument. I have tried to escape this using "\" like so:

printf "\---- %.55s\n" "$1 --------------"

The following is the result:

\---- content of $1 -------

As you can see the "\" became part of the output which is not what I want.

So the question is, how can i persuade printf that I am not trying to pass a long argument?

  • Replacing any - in the format string with their octal representation (here, \055) should work. It's admittedly not the cleanest, though. As in printf '\055\055\055\055\055 %.55s\n' "$1 --------------" – fra-san Nov 1 '18 at 9:50
  • 1
    I found out shortly after that just putting a double hyphen "--" before the actual string worked. – Lennart Rolland Nov 1 '18 at 9:59

To avoid an argument starting in - being interpreted as an option, you have a few different alternatives:

1) Move the minus signs form the format string to the argument string, possibly reflecting the new length of the printed string in the %.s format specifier. As in:

$ printf "%.60s\n" "---- $1 --------------"

2) bash's builtin commands accept -- as an option that instructs them to stop processing options and consider everything that follows as file-names and arguments. As in:

$ printf -- "---- %.55s\n" "$1 --------------"

3) You can substitute the minus signs with their octal codes. Actually, replacing just the first one works, as in:

$ printf "\055--- %.55s\n" "$1 --------------"
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.