Bash Printf Function Tutorial with Examples

Bash provides programming features to make Linux system administrator’s life easier. printf is one of the most used function used by Linux bash programmers. In this tutorial we will look Linux bash printf features and use cases while developing bash programs. Bash printf function is very similar to the C printf function.

Print

We can use printf function easily by providing the text in double quotes. In this example we will print Hello Poftut .

1

printf"Hello Poftut"

Print Given Text

We can provide parameters to print text. We will use %s as text specifier in printf function.

1

printf"Hello %s""Poftut"

This will print

1

Hello Poftut

Print Multiple Given Text

We can also provide multiple parameters to the printf command. In this example we will print to the Poftut , ismail ,ahmet .

1

printf"Hello %s ""Poftut""ismail""ahmet"

This will print

1

Hello PoftutHello ismailHello ahmet

Print Integer Numbers

We can also print integer type values with bash printf function. We will use %d to print integer values. In this example we will print the age variable.

1

printf"My age is %d"22

This will print

1

My age is22

Print Float Numbers

We can print float type values with bash printf function too. We will use %f to print float values. In this example we will print the price variable.

Format Specifiers

We can use format specifiers to print given text or numeric values. We will can specify the floating point decimal part and floating point part with . . In this example we will print only 2 numbers from floating point parts.

1

printf"Price is %2.2f"1.98765

This will print

1

Price is1.99

Justify Left

We may need to align the given text to the left. In this situation we will use - to justify left.