Dashes in printf

I’m trying to use printf to format some pretty output in a bash script

e.g.:

-----------------------  
| This is some output | 
-----------------------

But I’ve stumbled over some behavior I don’t understand.

$ printf "--"

gives me the error:

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

and

$ printf "-stuff"

results in

-bash: printf: -s: invalid option

So apparently printf thinks I’m trying to pass some arguments while I’m not.

Meanwhile, completely by accident, I’ve found this workaround:

$ printf -- "--- this works now ----n"

gives me

--- this works now ----

Can anyone explain this behavior?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The -- is used to tell the program that whatever follows should not be interpreted as a command line option to printf.

Thus the printf "--" you tried basically ended up as printf with no arguments” and therefore failed.

Method 2

-- is being interpreted as an option (in this case, to signify that there are no more options).

A format string should always be included when using printf to prevent bad interpretation. For your particular case:

printf '%sn' '-----------------------'

Method 3

There are differences between printf builtin and /usr/bin/printf, the second one do “what you mean” without these annoying errors.

printf "-----"             # error
printf -- "-----"          # ok
/usr/bin/printf "-----"    # ok
/usr/bin/printf -- "-----" # ok

Method 4

POSIX provides the option of using octal encoding.

 printf "--"

can become:

printf "55-"

This is a portable way to avoid the ambiguity of whether -- is being used as a format string or as a marker for the end of options.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x