0

When using printf in bash, does one always have to supply a format string as here.

printf "" "V01 Oct 2021"

Or would printf "V01 Oct 2021" still be ok?

1 Answer 1

6

I would strongly recommend you use a format string with printf. For example,

printf '%s' 'V01 Oct 2021'        # V01 Oct 2021

If you use an empty format string, you'll get an empty result because there is no instruction to print the parameter:

printf '' 'V01 Oct 2021'          # (nothing)

In this next case, since your string does not contain any format control characters you can use just a format string with no parameter value:

printf 'V01 Oct 2021'             # V01 Oct 2021

However, if you are interpolating a variable it should never go into the format string, just in case it starts with - or contains % or \ characters (or other characters whose encoding contains that of % or \ with most printf implementations including bash's builtin one). For example,

d=5; a="Increase by $d%"

printf "$a"                       # -bash: printf: `%': missing format character
printf "$a\n"                     # -bash: printf: `\': invalid format character
printf '%s\n' "$a"                # Increase by 5%
printf 'Increase by %d%%\n' "$d"  # Increase by 5%

Notice in the second of these examples that \n is not in itself invalid, but the % symbol at the end of $a confuses printf.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .