Escaping hyphens (–) with printf in bash

bash

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?

Best Answer

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