5

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.

2

1 Answer 1

12

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.

3
  • 2
    And the format is used at least once even if there's no argument, which is annoying in cases like printf '* %s\n' "$@" which you have to work around with [ "$#" -eq 0 ] || printf '* %s\n' "$@". Commented Aug 19, 2017 at 8:50
  • The zero argument case is a bit of a pain. but another way is to always have at leas tone argument. For example a solution to the last comment... printf "'%s' " "$0" "$@" Commented Jul 23, 2019 at 7:49
  • man bash is different from implementation to implementation. people looking for a static source can figure it out from here, the first and second items in the hyphen list Commented Oct 27, 2019 at 17:13

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.