Whilst there are many tools for text formatting, printf is unique and universal.

Learn all about printf in Bash to format your text just the right way!

To have the same tool available in Bash is of great benefit.

Terminal window showing the manual page for the Mutt email client on Linux

printf allows you to control and produce complex output formats, just the way you want it.

No problem, printf can do it and much more.

It could also output the text to a specific column on the screen, etc.

Article image

Shutterstock/gilangtristiano

Let’s have a look at these first.

For a full list of available interpreted sequences, seeman printf.

The most common ones arenfor newline,tfor tab and\for a backslash.

Printing a well formatted float with printf

In the options format above we also saw how we can specify flags.

We also inserted a space (as a flag) in between%and the width definition.

This led to the negative number inVAR1to be printed using a negative sign.

Printing a formatted float with printf using a Bash variable

So how can we ensure that we have leading zeros or spaces, while still having a specific length?

The output indeed yields leading zeroes, up to the defined length.

This remains the same even if we would use leading zeroes.

Printing negative numbers with printf and formatting

It also remains the same if no length is specified.

The usability of the space flag may thus in some cases (negative numbers) be limited.

Conclusion

Using printf from within Bash scripts or at the command line can yield clear well-defined output.

Output formatting for printf and leading zeroes definition

Enjoy printing well-formatted data with printf!

A leading space in positive numbers based on the special space flag