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

printf

printf is like filling in a form with blanks for names and numbers, so your output comes out exactly the shape you planned. Unlike echo, it will not press Enter for you at the end.

In this page:

  1. printf
Syntax
bash
printf "format string\n" argument1 argument2
# %s string, %d integer, %.2f decimal

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"
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting \n in the format string, since printf does not add a newline by itself.
  2. Passing the wrong number of arguments, so the format is reused or fields are empty.
  3. Using user input as the format string, as in printf "$input", which can break on %; use printf '%s\n' "$input".

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.