13

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?

1
  • 1
    I found out shortly after that just putting a double hyphen "--" before the actual string worked. Commented Nov 1, 2018 at 9:59

1 Answer 1

14

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 --------------"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .