Back to the command reference

printf

ShellFundamentals In simulator In real Linux

Print formatted text

Name: printf = print formatted

You can practise it right away in the simulator, and use it in real Linux mode too.

Description

printf prints text according to a format string, much like C's printf: %s strings, %d integers, %f decimals, with optional width and precision. It adds no newline; write \n yourself.

It behaves more consistently across systems than echo, so scripts use it when output format matters.

Syntax

printf FORMAT [ARGUMENT]...

Common options

%sString
%dInteger
%5.2fFloat: width 5, 2 decimals
%-10sLeft-aligned, 10 characters wide (right-aligned without -)
%x / %oAn integer in hexadecimal / octal
%%A % sign itself
\nNewline (printf doesn't add one)
-v VARStore the result in VAR instead of printing it (bash builtin)

Examples

  • $ printf "%s is %d years old\n" Tom 12

    Formatted output

    Explain
  • $ printf "%05d\n" 42

    Zero-pad to 5 digits: 00042

    Explain

Related