Safe printf format strings
How it works
printf treats its first format operand as instructions, not ordinary text. A fixed format such as printf '%s\n' "$message" prints the value as data, preserving percent signs and backslashes. Quoting a variable protects it from shell splitting, but does not stop printf from interpreting it when it is used as the format. In Bash, %b intentionally interprets escapes in an argument; %s does not. Prefer %s for text whose contents should not be interpreted.
Run each example separately in a fresh noninteractive Bash script with default options. Tested on Bash 5.2.37 with C locale. Do not enter the prompt or the expected output as code.
Keep percent and backslash literal
message='Progress: 50%\n'printf '%s\n' "$message"Expected stdout (tabs are real characters):
Progress: 50%\nThe data contains a literal percent and a backslash followed by n. Only the format newline becomes a real newline.
A format is not data
message='Rate: 100%%'printf "$message"printf '\n'printf '%s\n' "$message"Expected stdout (tabs are real characters):
Rate: 100%Rate: 100%%The first call interprets %% as one percent sign. The middle call prints only a newline; the final call with a fixed format preserves both percent signs. The first call is an intentional bad example with controlled input.
Choose %s or %b deliberately
message='A\nB'printf '%s\n' "$message"printf '%b\n' "$message"Expected stdout (tabs are real characters):
A\nBAB%s preserves the two-character escape notation; %b interprets it as a newline. %b is suitable only when interpreting escapes is intended.
Common mistakes
Never treat arbitrary text as a format string merely because it is double-quoted. Formats can contain conversions, escapes and options with special meaning. Use a fixed format beginning with %s, such as printf '%s\n' "$message".
Practice
Store the literal text Done: 75%\t in a variable and print it without interpreting the percent or backslash.
Next: Expansion and substitution