Reputation: 22560
I'm trying to concatenate strings in bash using printf
by following the examples here:
$ printf "%s " "hello printf" "in" "bash script"
The above works. But when I try to add to the format string some dashes (-
):
$ printf "--file=%s " "hello printf" "in" "bash script"
it generates an error:
sh: printf: --: invalid option
Obviously, it's treating the format string as an option. How can I include dashes -
into the output?
(I tried to add use \-
to escape the dashes, to no avail.)
Upvotes: 10
Views: 4342
Reputation: 85895
Always specify end of command line flags when using strings involving --
. In general the shell commands need to know where their positional argument start at. So by forcing --
after printf
we let it know that the subsequent arguments are to be interpreted as its arguments. At this point, afterwards using --
will be treated literally instead of being considered as a command line switch.
so define your printf
as
printf -- "--file=%s " "hello printf" "in" "bash script"
Also if you are planning to specify multiple printf
argument strings,do not include them in same format specifier. You might need this
printf -- "--file=%s %s %s" "hello printf" "in" "bash script"
See more on The printf command in bash
Upvotes: 12