man printf.1
has a note: "... your shell may have its own version of printf
...". This question is tagged for bash
, but, if at all possible, I'm trying to write scripts portable to any shell. dash
is generally a good minimal base for portability, so the answer here works in bash
, dash
and & zsh
. If the script works in these 3, it is most likely portable anywhere.
The last printf
implementation in dash
[1] does not colorize the output, given the %s
format specifier with the ANSI \e
escape character, but the %b
format specifier combined with the octal \033
(equivalent to ASCII ESC
) will do the job. Please comment on any outliers, but, AFAIK, printf
is implemented in all shells to use the octal subset of ASCII at a minimal level.
To the title of the question "Using colors with printf", the most portable way to specify formatting is to combine the %b
format specifier for printf
(as indicated in the previous answer by @Vlad) with the octal escape \033
.
portable-color.sh
#/bin/sh P="\033[" BLUE=34 printf "-> This is %s %-6s %s text \n" $P"1;"$BLUE"m" "blue" $P"0m" printf "-> This is %b %-6s %b text \n" $P"1;"$BLUE"m" "blue" $P"0m"
Outputs:
$ ./portable-color.sh -> This is \033[1;34m blue \033[0m text -> This is blue text
... and "blue" is blue in the second line.
%-6s
format %-6s
of the OP is in the middle of the format string between the sequences of control characters for opening and closing.
[1] Link: man dash
Section "Builtins" :: "printf" :: "Format"
AaronDanielson Jul 13 '18 at 17:46 2018-07-13 17:46
source share