mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 11:19:45 +08:00
Created SC2059 (markdown)
30
SC2059.md
Normal file
30
SC2059.md
Normal file
@@ -0,0 +1,30 @@
|
||||
# Don't use variables in the printf format string. Use printf "..%s.." "$foo".
|
||||
|
||||
### Problematic code:
|
||||
|
||||
printf "Hello, $NAME\n"
|
||||
|
||||
### Correct code:
|
||||
|
||||
printf "Hello, %s\n" "$NAME"
|
||||
|
||||
### Rationale:
|
||||
|
||||
`printf` interprets escape sequences and format specifiers in the format string. If variables are included, any escape sequences or format specifiers in the data will be interpreted too, when you most likely wanted to treat it as data. Example:
|
||||
|
||||
coverage='96%'
|
||||
printf "Unit test coverage: %s\n" "$coverage"
|
||||
printf "Unit test coverage: $coverage\n"
|
||||
|
||||
The first printf writes `Unit test coverage: 96%`.
|
||||
|
||||
The second writes ``bash: printf: `\': invalid format character``
|
||||
|
||||
### Contraindications
|
||||
|
||||
Sometimes you may actually want to interpret data as a format string, like in:
|
||||
|
||||
hexToAscii() { printf "\x$1"; }
|
||||
hexToAscii 21
|
||||
|
||||
Like all warnings, you can selectively silence this warning with a [directive].
|
Reference in New Issue
Block a user