Why does `printf "%s"` concatenate two following strings together?

That’s how printf is specified to behave:

The format operand shall be reused as often as necessary to satisfy the argument operands. Any extra b, c, or s conversion specifiers shall be evaluated as if a null string argument were supplied; other extra conversion specifications shall be evaluated as if a zero argument were supplied. If the format operand contains no conversion specifications and argument operands are present, the results are unspecified.

In your case, the %s format is repeated as many times as necessary to handle all the arguments.

printf "%s" a b

and

printf "%s%s" a b

produce the same result because in the first case, %s is repeated twice, which is equivalent to %s%s.


If you supply more parameters to printf than the format string expects then the format string is repeated.

For example

$ printf "%s -- %s" a b c d e
a -- bc -- de -- 

We can see that the %s -- %s format is effectively repeated.

This can be useful; eg for formatting

$ printf "%s -- %s\n" a b c d e
a -- b
c -- d
e -- 

Tags:

Printf

Bash