HxHippy

printf

Format and print data

Overview

Formats and prints data according to a specified FORMAT string, similar to the C printf function. It offers more control over output formatting than `echo` and always interprets backslash escapes.

Syntax

printf FORMAT [ARGUMENT]...

Common Options

FORMAT string

A string containing literal characters, backslash escapes (e.g., \n, \t), and format specifiers (e.g., %s, %d, %.2f).

%s

Format specifier for a string.

%d, %i

Format specifier for a signed decimal integer.

%f

Format specifier for a floating-point number (decimal notation).

%x, %X

Format specifier for a hexadecimal integer (lowercase or uppercase).

%c

Format specifier for a single character.

%%

Literal percent sign.

Width/Precision

Modifiers like %10s (min width 10), %.2f (2 decimal places), %-10s (left-justify).

Note

`printf` reuses the FORMAT string if more ARGUMENTs are provided than specifiers. It does not automatically add a newline; use \n.

Examples

$ printf "Name: %s, Age: %d\n" "Alice" 30

Prints "Name: Alice, Age: 30" followed by a newline.

$ printf "%-10s | %03d\n" "CPU" 7 "RAM" 45

Formats output in columns: "CPU | 007\nRAM | 045".

$ printf "Value: %.2f\n" 123.4567

Prints "Value: 123.46".

$ printf "Hex: %#x, Octal: %#o\n" 16 16

Prints "Hex: 0x10, Octal: 020" (with base prefixes).

$ printf "An important message" >&2

Redirects the message to standard error (stderr).

$ printf "Var: %s\n" "${vars[@]}"

Iterates through array elements, printing each on a new line prefixed by "Var: ".

$ printf 'Current time: %(%T)T\n' -1

(Bash specific) Prints current time, e.g., "Current time: 14:30:55".

$ printf 'The item is \'%s\'.\n' "book"

Prints "The item is 'book'." demonstrating single quote escaping.

printfformatprintdisplayoutputstringshellscript