Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
1  
See also unix.stackexchange.com/questions/11376/… –  manatwork Oct 17 '11 at 11:51
    
Out of intereset, are there any implementations of echo that would fail when doing echo ------------? Most only support -n (no trailing newline), -e (interpret backslash-escaped chars) and possible -E (do NOT interpret them) and do not error out when other option-like arguments are encountered, right? (EDIT: GNU's /bin/echo also supports --help and --version.) –  janmoesen Oct 18 '11 at 6:34

2 Answers 2

up vote 15 down vote accepted

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

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

share|improve this answer
3  
In other words, to print -- you can run printf -- --. –  l0b0 Oct 17 '11 at 12:14
1  
... and printf -- is the same as printf (you get the same message) –  Peter.O Oct 17 '11 at 14:54
    
Just a technicality, but you mean shouldn't be interpreted as an option, not an argument. –  Chris Down Nov 7 '11 at 13:06
    
Yes, right, thanks. Edited. –  sr_ Nov 7 '11 at 13:24

-- 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 '%s\n' '-----------------------'
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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