Shell printf Command

In the previous chapter we learned about the Shell echo command. In this chapter, we will learn about another Shell output command, printf.

printf(print formatted) is a Shell command for formatted output, derived from the C language'sprintf()function.

andechoUnlike,printfit does not automatically add newlines, and can precisely control the output format.

printf is defined by the POSIX standard, so scripts using printf are more portable than those using echo.

printf uses quoted text or space-separated arguments, and you canprintfuse format strings in it, and also specify string width, left/right alignment, etc. By default, printf does not,echoautomatically add newlines; we can add them manually.\n。

Why use printf?

  1. Format control: Can specify field width, precision, and alignment.
  2. Type safety: Different types of data (integers, floats, strings, etc.) have corresponding format specifiers.
  3. Portability: Behavior is more consistent across different systems and shells.
  4. Complex output: Suitable for generating structured output such as tables and reports.

Basic Syntax

The syntax of the printf command:

printf  format-string  [arguments...]

Parameter description:

  • format-string: A string containing ordinary characters and format specifiers.
  • arguments...: Variables or values corresponding to format specifiers.

Format specifiers start with a%character, followed by one or more characters, used to specify the output format. Common format specifiers include:

  • %s: String
  • %d: Decimal integer
  • %f: Floating-point number
  • %c: Character
  • %x: Hexadecimal number
  • %o: Octal number
  • %b: Binary number
  • %e: Floating-point number in scientific notation

Workflow

  1. Parse the format string; output ordinary characters directly when encountered.
  2. When a format specifier (starting with%at the beginning) is encountered:
    • Read the next argument.
    • Process the argument according to the format specified by the specifier.
    • Insert the result into the output.
  3. After processing all format specifiers, output the final result.

Practical Examples

1. Basic Usage

Example

# Simple string output
printf "Hello, World!\n"

# Output with variables
name="Alice"
printf "Hello, %s\n" "$name"

Execution and output:

Example

$ bash script.sh
Hello, World!
Hello, Alice

2. Common Format Specifiers

Example

# Integer
printf "Decimal: %d\nHex: %x\nOctal: %o\n" 255 255 255

# Floating point
printf "Float: %f\nScientific: %e\n" 3.14159 3.14159

# String
printf "Name: %s\n" "Bob"

# Character
printf "First letter: %c\n" "A"

Execution result:

Decimal: 255
Hex: ff
Octal: 377
Float: 3.141590
Scientific: 3.141590e+00
Name: Bob
First letter: A

3. Formatting Control

Example

# Field width and alignment
printf "|%10s|\n|%-10s|\n" "right" "left"

# Leading zeros in numbers
printf "Year: %04d\n" 23

# Floating-point precision
printf "Pi: %.2f\n" 3.14159

Execution result:

|     right|
|left      |
Year: 0023
Pi: 3.14

4. Multiple Argument Handling

Example

printf "%-10s %5d %8.2f\n" "Apple" 5 2.5 "Orange" 3 1.75

Execution result:

Apple          5     2.50
Orange         3     1.75

Extended Applications

1. Creating Table Output

Example

#!/bin/bash

# Header
printf "%-15s %10s %10s %10s\n" "Item" "Quantity" "Price" "Total"

# Separator line
printf "%-15s %10s %10s %10s\n" "---------------" "----------" "----------" "----------"

# Data rows
printf "%-15s %10d %10.2f %10.2f\n" "Notebook" 3 2.50 7.50
printf "%-15s %10d %10.2f %10.2f\n" "Pen" 5 1.20 6.00
printf "%-15s %10d %10.2f %10.2f\n" "Eraser" 2 0.50 1.00

# Total row
printf "%-15s %10s %10s %10.2f\n" "" "" "Total:" 14.50

Output effect:

Item            Quantity      Price      Total
--------------- ---------- ---------- ----------
Notebook               3       2.50       7.50
Pen                    5       1.20       6.00
Eraser                 2       0.50       1.00
                       Total:             14.50

2. Progress Bar Implementation

Example

#!/bin/bash

for i in {1..20}; do
    printf "\rProgress: [%-20s] %d%%" $(printf "%${i}s" | tr ' ' '#') $((i*5))
    sleep 0.1
done
printf "\n"

Execution effect: Displays a gradually growing progress bar.

3. Color Output

Example

#!/bin/bash

RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color

printf "${RED}Error:${NC} Something went wrong\n"
printf "${GREEN}Success:${NC} Operation completed\n"

4. Formatted Output

Next, I will use a script to demonstrate the powerful features of printf:

Example

#!/bin/bash
# author: Example
# url:www.example.com
 
printf "%-10s %-8s %-4s\n"Name Gender Weightkg
printf "%-10s %-8s %-4.2f\n"Guo Jing Male66.1234
printf "%-10s %-8s %-4.2f\n"Yang Guo Male48.6543
printf "%-10s %-8s %-4.2f\n"Guo Fu Female47.9876

Execute the script, and the output is as follows:

姓名     性别   体重kg
郭靖     男      66.12
杨过     男      48.65
郭芙     女      47.99

%s %c %d %fThese are all format specifiers.%sOutputs a string,%dinteger output,%coutputs a character,%foutputs a real number in decimal form.

%-10sRefers to a width of 10 characters (-Indicates left alignment; without it, right alignment is used. Any characters will be displayed within a width of 10 characters. If insufficient, spaces are automatically padded; if exceeded, the content is still displayed completely.

%-4.2fRefers to formatting as a decimal, where.2Refers to keeping 2 decimal places.

Example

#!/bin/bash
# author: Example
# url:www.example.com
 
# format-string uses double quotes
printf "%d %s\n" 1 "abc"

# Single quotes have the same effect as double quotes
printf '%d %s\n' 1 "abc"

# Output can also be done without quotes
printf %s abcdef

# The format specifies only one argument, but the extra arguments are still output according to that format; format-string is reused
printf %s abc def

printf "%s\n" abc def

printf "%s %s %s\n" a b c d e f g h i j

# If there are no arguments, %s is replaced by NULL and %d by 0
printf "%s and %d \n"

Execute the script, and the output is as follows:

1 abc
1 abc
abcdefabcdefabc
def
a b c
d e f
g h i
j  
 and 0

printf Escape Sequences

SequenceDescription
\aAlert character, usually the ASCII BEL character.
\bBackspace
\cSuppresses (does not display) any trailing newline character in the output result (only valid in argument strings controlled by the %b format specifier). Moreover, any characters remaining in the argument, any subsequent arguments, and any characters remaining in the format string are ignored.
\fForm feed
\n Newline
\rCarriage return
\tHorizontal tab
\vVertical tab
\\A literal backslash character
\ddd A character representing a 1 to 3 digit octal value. Only valid in the format string.
\0dddA character representing a 1 to 3 digit octal value.

Example

$ printf "a string, no processing:<%s>\n" "A\nB"
a string, no processing:<A\nB>

$ printf "a string, no processing:<%b>\n" "A\nB"
a string, no processing:<A
B>

$ printf "www.example.com \a"
www.example.com $                  # No newline

Summary of Key Points

Key Knowledge Review

Concept Description Example
Basic syntax printf "format" args printf "%s" "hello"
Format specifier Starts with %, specifies data type and format. %d(integer),%f(floating point)
Escape character Special character representation \n(newline),\t(tab)
Field width Controls the minimum width of output %10s(10 characters wide)
Precision control Number of decimal places for floating-point numbers %.2f(2 decimal places)

Common Format Specifiers Quick Reference Table

Specifier Purpose Example input Example output
%s String "text" text
%d Decimal integer 255 255
%x Hexadecimal integer 255 ff
%f Floating-point number 3.14159 3.141590
%.2f 2 decimal places 3.14159 3.14
%c Single character "A" A
%% Percent sign - %
Other extensions