Home > OS >  printing text without use of format string in bash
printing text without use of format string in bash

Time:05-05

Have been doing printf "text" to print some text from a bash script. Is using printf without a format string valid to do?

CodePudding user response:

Putting the entire message in the format string is a reasonable thing to do provided it doesn't contain any dynamic data. As long as you have full control over the string (i.e. it's either just a fixed string, or one selected from a set of fixed strings, or something like that), and you've used that control to make sure it doesn't contain any unintended escape characters, all % characters in it are doubled (making them literal, rather than format specifiers), and the string doesn't start with -.

Basically, if it's a fixed string and it doesn't obviously fail, it'll work consistently.

But if it contains any sort of dynamic data -- filenames, user-entered data, anything at all like that -- you should put format specifiers in the format string, and the dynamic data in separate arguments.

So these are ok:

printf 'Help, Help, the Globolinks!\n'
printf 'Help, Help, the %s!\n' "$monster_name"

But this is not:

printf "Help, Help, the $monster_name!\n"    # Don't do this
  • Related