12

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.)

1

1 Answer 1

14

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

Sign up to request clarification or add additional context in comments.

4 Comments

The single %s is intentional, I'm guessing. printf will repeat the format string if there are extra arguments. "--file=%s " a b c produces --file=a --file=b --file=c.
@JohnKugelman: Yeah I wasn't sure, that's why include a word might need to it.
Given the arguments in the example, it's far more likely the OP wants for f in "hello printf" "in" "bash script"; do args+=(--file "$f") rather than printf at all.
Good point. "--file=%q " would also work. Though an array is better.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.