The code "%$width.${width}s\n"
generates a format string that is suitable for consumption by printf
In the script that you posted, width
has been assigned the value 55
, so that both $width
and ${width}
are expanded by bash to 55
: the entire first parameter to printf
expands to %55.55s\n
; this is the format %s
, with a field width and precision specifiers that ask to print on exactly 55 characters. Given the value of variable divider
at this point, this will simply print a line of 55 equal signs. A perhaps simpler way of printing the same thing would have been perl -e 'print "=" x 55, "\n"'
.
The simplest form for the field width specifier is an integer: this asks printf
to use at least this many characters for printing. If the corresponding parameter requires fewer characters than this to print, then the output is left-padded with spaces.
The simplest form for the precision specifier is a dot followed by an integer: when applied to %s
, this sets the maximum number of characters to print. (It has a different meaning for numeric types.)
In response to a comment, I will also mention a little bit about shell variable expansion (the complete explanation can be found by searching for "parameter expansion" in the bash documentation, see also $VAR vs ${VAR} and to quote or not to quote):
When a variable, say x
, has been set, then $x
expands to the value of x
. If that value contains whitespace, then the expansion will be several words. This is why it's important in the code above that, for example, "$format"
is within double quotes: this forces the expansion to be a single word (otherwise, printf
would see a first parameter %-15s
, followed by an argument %8s
, etc., instead of receiving the entire format string as a single parameter).
It is permissible to write ${x}
instead of just $x
to expand the variable x
; in the case above, "${width}s"
, it is necessary to do so because if one had written "$widths"
, then bash would try to get the value of variable widths
, which is unset, resulting in an empty expansion.