printf#

printf takes a format specifier as the first argument, and substitutes the following arguments in the format repeatedly, giving us complete control of the output. We’ll look into the two main placeholders used in the format specifier, %s and %q. See man 1 printf for more details.

%s - String#

Let’s deconstruct that format specifier:

  • %s formats an argument as a string. This is the part of the format string which is replaced by subsequent arguments (from the $names array variable in the above code).

  • The rest of the string (the prefix “Name: ” and the escaped newline “\n”) is printed as–is every time the format is repeated.

To reproduce this with echo we would have to loop over the entries in the array manually. Analogous to HTML and CSS in web development, printf cleanly separates the content (the $names array) from the formatting (the “Name: ” prefix, string substitution and newline suffix).

%q#

We can also put several % format specifiers within a format string to consume more than one entry at a time. One handy use case for this is if we have an array with pairs of keys and values, and want to create a Bash configuration file with key=value assignments to source later. Let’s try it using the %s format specifier:

 

This page is a preview of The newline Guide to Bash Scripting

No discussions yet