Mastering Linux printf: Formats, Escape Sequences, and Real-World Examples
This guide explains why printf outperforms echo in shell scripts, details its syntax, lists essential escape characters and conversion specifiers, and provides multiple practical examples—including numeric bases, floating‑point formatting, tabular output, and colored alignment—to help you format command‑line output precisely.
When writing shell scripts, echo can only print simple text, while printf offers full control over output formatting, making it the preferred command for structured data.
The general syntax is printf format [arguments...], where the format string contains conversion specifiers such as %s for strings and %d for decimal integers, and literal characters like \n for newlines must be added manually.
Example – printing personal information :
printf "姓名:%s
身高:%dcm
体重:%dkg
" "小明" "180" "75"
# Output:
姓名:小明
身高:180cm
体重:75kgCommon escape characters : \" – escaped double quote \\ – escaped backslash \b – backspace \n – newline \r – carriage return \t – horizontal tab \v – vertical tab %% – literal percent sign
Common conversion specifiers : %d – decimal integer %f – floating‑point number %s – string %x – hexadecimal integer %o – octal integer
Example 1 – numeric bases :
printf "Decimal: %d
Hex: %x
Octal: %o
" 100 100 100
# Output:
Decimal: 100
Hex: 64
Octal: 144Example 2 – floating‑point precision :
printf "%.2f
" 3.1415926
# Output:
3.14Example 3 – tabular output with extra arguments :
printf "%s \t %s \t %s
" "姓名" "性别" "年龄" "小明" "男" "18" "小红" "女" "19" "小蓝" "男" "18"
# Output:
姓名 性别 年龄
小明 男 18
小红 女 19
小蓝 男 18Example 4 – field width, alignment, and color :
# Left‑aligned fields (width 10)
printf "\e[1;30;47m%-10s %-10s\e[0m
" "姓名" "年龄"
# Colored rows with specific widths
printf "\e[36;47m%-10s %-8d\e[0m
" "小明" 18
printf "\e[31;47m%-10s %-8d\e[0m
" "小红" 19
printf "\e[34;47m%-10s %-8d\e[0m
" "小蓝" 19These examples demonstrate how printf can format text, numbers, and colors precisely, making it a powerful tool for producing readable command‑line output.
End of tutorial.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
