Shell – How printf with Multiple Arguments Separated by Space Works

printfshell

I have the following printf function:

$ printf '%s %s %s\t%s\n' 100644 blob 8e1e f1.txt 100644 blob 9de7 f2.txt | git mktree

Can anyone please explain what it produces and why? I expected to have equal number of formatting options %s for each argument string but I have a lot more arguments strings here.

Best Answer

The format is reused as many times as needed to display all arguments. If there are too few arguments, the missing arguments are treated as empty strings.

Examples

Here is an example of a format that specifies two arguments but only one is provided:

$ printf '%s ; %s ;\n' a
a ;  ;

Here is the same format, this time provided with one too many arguments:

$ printf '%s ; %s ;\n' a b c
a ; b ;
c ;  ;

Here is the example from the question in which the format expects four arguments. Since eight arguments are provided the entire format is used twice:

$ printf '%s %s %s\t%s\n' 100644 blob 8e1e f1.txt 100644 blob 9de7 f2.txt
100644 blob 8e1e        f1.txt
100644 blob 9de7        f2.txt

Documentation

From man bash:

The format is reused as necessary to consume all of the arguments. If the format requires more arguments than are supplied, the extra format specifications behave as if a zero value or null string, as appropriate, had been supplied. The return value is zero on success, non-zero on failure.

Related Question