printf格式字符串中的可变插值与替换

时间:2015-09-18 10:48:33

标签: shell printf shellcheck

如果您将变量放在printf(1)格式字符串中,

ShellCheck会发出警告。为什么呢?

时:

printf "$file does not exist\n"

在某种程度上低于:

printf "%s does not exist\n" "$file"

1 个答案:

答案 0 :(得分:4)

因为理论上file变量可能有一些格式化字符会导致printf失败。这些例子将使其更加清晰:

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

根据建议,它可以正常工作:

printf "%s does not exist\n" "$file"
m%y does not exist