How to use printf and %s when there are color codes?
fail_color="\033[31;1m"
color_end="\033[0m"
function="foo"
line_number="42"
printf "%bError - Function: %s, Line: %d%b\n" "$fail_color" "$function" "$line_number" "$color_end"
Output:
Error - Function: foo, Line: 42
Tested with Ubuntu 11.04 (bash 4.2.8(1)-release), Ubuntu 14.04.1 LTS (bash 4.3.11(1)-release), RHEL 5.1 (bash 3.1.17(1)-release), RHEL 6.0 (bash 4.1.2(1)-release), RHEL 7.0 (bash 4.3.11(1)-release) and Solaris 11 (bash 4.1.9(1)-release)
I like Cyrus's answer, but this syntax also works:
#!/usr/bin/env bash
fail_color=$'\033[31;1m'
color_end=$'\033[0m'
function="foo"
line_number="42"
printf "%sError - Function: %s, Line: %d%s\n" "$fail_color" "$function" "$line_number" "$color_end"
And ShellCheck says "It all looks good!". :)