printf

printf is possibly more useful even than echo, although echo is a little bit more straightforward. One of the main features of printf is its ability to process C-style text-padding. This can be useful in displaying columnar data or just lining data up with other displayed elements. For example, the formatting string %-10s means a left-aligned string, at least 10 characters wide.

As an easy way to read entries from /etc/passwd, this script uses the IFS variable to tell read that the delimiter is the colon character, and then passes those variables to printf, which displays them with appropriate padding. Notice that the avahi-autoipd and Debian-exim accounts have more than ten characters, so the output is shifted along to the right and not trimmed. Similarly, the gnats and timidity GECOS (“name”) fields are more than 30 characters, so their shells get shifted to the right.

cat printf1.sh
#!/bin/bash
printf "%-10s %-30s %-10s\n" "Username" "Name" "Shell"
cut -d: -f1,5,7 /etc/passwd | while IFS=: read uname name shell
do
  printf "%-10s %-30s %-10s\n" "$uname" "$name" "$shell"
done
$ ./printf1.sh Username   Name                           Shell root       root                           /bin/bash daemon     daemon                         /bin/sh bin        bin                            /bin/sh sys        sys                            /bin/sh sync       sync                           /bin/sync games      games                          /bin/sh man        man                            /bin/sh ...

Get Shell Scripting: Expert Recipes for Linux, Bash, and More now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.