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

roj*_*oke 5 shell printf shellcheck

如果在printf(1)格式字符串中放入变量,ShellCheck会发出警告。为什么?

是:

printf "$file does not exist\n"
Run Code Online (Sandbox Code Playgroud)

在某些方面不如:

printf "%s does not exist\n" "$file"
Run Code Online (Sandbox Code Playgroud)

anu*_*ava 6

因为理论上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
Run Code Online (Sandbox Code Playgroud)

根据建议,它将正常工作:

printf "%s does not exist\n" "$file"
m%y does not exist
Run Code Online (Sandbox Code Playgroud)