5

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

thor
  • 21,418
  • 31
  • 87
  • 173
  • Why not using [string concatenation](https://stackoverflow.com/questions/4181703/how-to-concatenate-string-variables-in-bash)? – Mladen B. May 17 '18 at 12:21

1 Answers1

8

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

Inian
  • 80,270
  • 14
  • 142
  • 161
  • 1
    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`. – John Kugelman May 17 '18 at 12:56
  • @JohnKugelman: Yeah I wasn't sure, that's why include a word _might need_ to it. – Inian May 17 '18 at 13:00
  • 2
    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. – chepner May 17 '18 at 13:16
  • Good point. `"--file=%q "` would also work. Though an array is better. – John Kugelman May 17 '18 at 13:26