Skip to content

printf

References:

https://linuxize.com/post/bash-printf-command/

Usage

printf "%s\n" arguments on separate lines

printf -v output_variable "%s\n" printing to a variable

Format Specifiers

%[flags][width].[precision]specifier

Flags

Value Remarks
- Left aligned
+ Prefix numbers with + or - signs. By default only negative numbers get the - sign
0 Pad numbers with leading zeros
blank Prefix positive numbers with blank space and negative numbers with a - sign

Width

Value Remarks
* When asterisk (*) is used as a width directive, the width value is taken from the arguments

Specifier values

Specifier Type
s string
b string, but escape sequences are translated
d signed decimal integer
u unsigned decimal integer
x unsigned hexadecimal (lowercase)
X unsigned hexadecimal (upercase)
c single character
f floating-point number
%% literal % symbol

Examples

Value Remarks
%s Print as string
%b Print as string with escape sequences (e.g. \n) translated
%8s 8-character width (right justified)
%-9s 9-character width (left justified)
%10.8s Width of 10-characters, string truncated at 8 characters