← Back to Bash Course | Chapter 3: Control Flow | Lesson 3 of 14

printf

In this page:

  1. printf

printf

printf formats output using format specifiers like %s (string), %d (integer), and %.2f (decimal), similar to C's printf. Unlike echo, it does not add a trailing newline automatically — you must include \n yourself. It gives much more precise control over output formatting than echo.

Note: Use printf instead of echo whenever you need aligned columns or fixed decimal places.

Example: printf

bash
#!/bin/bash
printf "Name: %s, Age: %d\n" "Alice" 30
printf "Pi is approximately %.2f\n" 3.14159
printf "%-10s|%5s\n" "left" "right"

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.