Use of variable in `printf` format stringSH-2059
Problematic code:
printf "Hello, $NAME\n"
Preferred code:
printf "Hello, %s\n" "$NAME"
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, where you might have wanted to treat them as data.
Example:
coverage='96%'
printf "Unit test coverage: %s\n" "$coverage"
printf "Unit test coverage: $coverage\n"
The first printf
writes the string Unit test coverage: 96%.
.
The second writes bash: printf:
': invalid format character`
Exceptions:
Sometimes you may actually want to interpret data as a format string, like in:
octToAscii() { printf "\\$1"; }
octToAscii 130
In Bash, Ksh and BusyBox, there's a %b
format specifier that expands escape sequences without interpreting other format specifiers: printf '%b' "\\$1"
.
In POSIX, you can instead ignore this warning.
Other times, you might have a pattern in a variable:
filepattern="file-%d.jpg"
printf -v filename "$filepattern" "$number"
In these cases, please ignore this issue using a # skipcq
pragma.