From 5eb94be94e4768f075e4eed82860593399848490 Mon Sep 17 00:00:00 2001 From: James Morris <6653392+J-M0@users.noreply.github.com> Date: Wed, 27 Sep 2023 08:57:02 -0400 Subject: [PATCH] printf %b is POSIX, so move that suggestion into the Rationale section --- SC2059.md | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/SC2059.md b/SC2059.md index 2d0a4f1..7781e1b 100644 --- a/SC2059.md +++ b/SC2059.md @@ -26,8 +26,6 @@ The first printf writes `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: ```sh @@ -35,13 +33,24 @@ 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. +In this case, use the `%b` format specifier that expands escape sequences without interpreting other format specifiers: -Other times, you might have a pattern in a variable: +```sh +octToAscii() { printf '%b' "\0$1"; } +octToAscii 130 +``` + +### Exceptions: + +Sometimes you might have a pattern in a variable: ```sh filepattern="file-%d.jpg" printf -v filename "$filepattern" "$number" ``` -This has no good rewrite. Please [[ignore]] the warning with a [[directive]]. \ No newline at end of file +This has no good rewrite. Please [[ignore]] the warning with a [[directive]]. + +### Related resources: + +* https://pubs.opengroup.org/onlinepubs/9699919799.2018edition/utilities/printf.html \ No newline at end of file