Book Image

Mastering Linux Shell Scripting

By : Andrew Mallett
Book Image

Mastering Linux Shell Scripting

By: Andrew Mallett

Overview of this book

Shell scripting is a quick method to prototype a complex application or a problem by automating tasks when working on Linux-based systems. Using both simple one-line commands and command sequences complex problems can be solved with ease, from text processing to backing up sysadmin tools. In this book, you’ll discover everything you need to know to master shell scripting and make informed choices about the elements you employ. Get to grips with the fundamentals of creating and running a script in normal mode, and in debug mode. Learn about various conditional statements' code snippets, and realize the power of repetition and loops in your shell script. Implement functions and edit files using the Stream Editor, script in Perl, program in Python – as well as complete coverage of other scripting languages to ensure you can choose the best tool for your project.
Table of Contents (21 chapters)
Mastering Linux Shell Scripting
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Formatting output


We have remained faithful to the print command so far, as we have been limited in what we require from the output. If we want to print out, say, the username, UID, and default shell we need to start formatting the output just a little. In this case, we can organize the output in well-shaped columns. Without formatting, the command we use will look similar to the following example where we use commas to separate the field that we want to print:

$ awk ' BEGIN { FS=":" } { print $1,$3,$7 } ' /etc/passwd

We use the BEGIN block here, as we can make use of it to print column headers later.

To understand the problem a little better, we can take a look at the following screenshot that illustrates the uneven column widths:

The issue that we have in the output is that the columns do not align, as the username is of an inconsistent length. To improve on this, we can use the printf function where we can specify the column width. The syntax for the awk statements will be similar to the...