Skip to Content
Shell Scripting: Expert Recipes for Linux, Bash, and More
book

Shell Scripting: Expert Recipes for Linux, Bash, and More

by Steve Parker
August 2011
Beginner to intermediate
600 pages
14h 29m
English
Wrox
Content preview from Shell Scripting: Expert Recipes for Linux, Bash, and More

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Linux Command Line and Shell Scripting Techniques

Linux Command Line and Shell Scripting Techniques

Vedran Dakic, Jasmin Redzepagic
Linux Shell Scripting Cookbook - Third Edition

Linux Shell Scripting Cookbook - Third Edition

Clif Flynt, Sarath Lakshman, Shantanu Tushar

Publisher Resources

ISBN: 9781118166321Purchase bookDownloads