10

This question already has an answer here:

$ printf "%s" a b
ab$ printf "%s%s" a b
ab

I have some problem understand the format specifier for printf. If I am correct it is mostly the same as those for strings in the C programming language.

Why does the format specifier %s concatenate the two following strings together?

Why does %s not mean that there is only one string to substitute it, and ignore the remaining string?

Why are the results for two strings under %s and under %s%s the same?

marked as duplicate by Isaac, thrig, RalfFriedl, filbranden, muru Nov 25 '18 at 5:54

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • What do you get if you do printf "%s 123" "hello" "world", yes it surprised me as well, but it is in the manual. – ctrl-alt-delor Nov 24 '18 at 18:00
14

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.

  • Does format specifier in C also work in the same or similiar way? – Ben Nov 24 '18 at 13:04
  • 6
    No, it doesn’t — it ignores extra arguments. Modern C compilers will warn about mismatches between the format string and the arguments. – Stephen Kitt Nov 24 '18 at 13:09
  • 5
    @Ben in C, the printf function is a variadic function: all the parameters but the first are accepted via .... This means that unless told via the first argument how many are present (and which types), the function can't ever know what the caller has passed to it. In the shell the command knows exactly how many command-line arguments it has. – Ruslan Nov 24 '18 at 14:32
8

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

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