Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable Interpolation vs. Substitution in printf Format String

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"
like image 667
rojomoke Avatar asked Sep 18 '15 10:09

rojomoke


1 Answers

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
like image 151
anubhava Avatar answered Nov 15 '22 09:11

anubhava