Search code examples
shellprintfshellcheck

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"

Solution

  • 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