6

ShellCheck gives a warning if you put a variable in the printf(1) format string. Why?

Is:

printf "$file does not exist\n"

inferior in some way to:

printf "%s does not exist\n" "$file"
Will
  • 24,082
  • 14
  • 97
  • 108
rojomoke
  • 3,765
  • 2
  • 21
  • 30

1 Answers1

8

Because in theory file variable can have some formatting character that will fail the printf. These examples will make it more clear:

file='my'
printf "$file does not exist\n"
my does not exist    

file='m%y'
printf "$file does not exist\n"
-bash: printf: `y': invalid format character

As per recommendedation it will work fine:

printf "%s does not exist\n" "$file"
m%y does not exist
anubhava
  • 761,203
  • 64
  • 569
  • 643