printf 格式字符串中的变量插值与替换
Variable Interpolation vs. Substitution in printf Format String
如果将变量放入 printf(1)
格式字符串中,ShellCheck 会发出警告。为什么?
是:
printf "$file does not exist\n"
在某些方面不如:
printf "%s does not exist\n" "$file"
因为理论上 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
printf(1)
格式字符串中,ShellCheck 会发出警告。为什么?
是:
printf "$file does not exist\n"
在某些方面不如:
printf "%s does not exist\n" "$file"
因为理论上 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