我有这些行:
if [[ $# -eq 0 ]]; then
printf "$fail_color Error - Function: $function, Line: $line_number \n"
printf "do_test: Third parameter missing - expected result\n"
exit 1
fi
这工作正常,给了我预期的输出Error - Function: words, Line: 94
然后我使用了 ShellCheck,它推荐
printf "$fail_color Error - Function: $function, Line: $line_number \n
^––SC2059 Don't use variables in the printf format string. Use printf "..%s.." "$foo".
所以我尝试将其更改为
printf "%s Error - Function: %s, Line: %s \n", "$fail_color", "$function", "$line_number"
但现在输出显示颜色代码详细信息而不是颜色:
\033[31;1m, Error - Function: words,, Line: 94
,do_test: Third parameter missing - expected result
相关 - 除了多个之外,是否有更好的方法来命名字符串%s
?
细节 - 颜色定义如下:
fail_color="\033[31;1m"
pass_color="\033[32;1m"
color_end="\033[0m"
答案1
fail="\033[31;1m"
color_end="\033[0m"
func="foo" # (renamed this variable to avoid confusion with function keyword)
line_number="42"
printf "%bError - Function: %s, Line: %d%b\n" "$fail" "$func" "$line_number" "$color_end"
输出:
错误 - 函数:foo,行:42
使用 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)-发行版)、RHEL 7.0 (bash 4.3.11(1)-发行版)和 Solaris 11 (bash 4.1.9(1)-发行版)
答案2
我喜欢赛勒斯的答案,但这种语法也有效:
#!/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"
ShellCheck 说“一切看起来都不错!”。 :)
答案3
这printf(1)
男人说:
%b ARGUMENT as a string with '\' escapes interpreted, except that octal escapes are of the form \0 or \0NNN
答案4
该变量"$fail_color"
在 之前包含太多或太少的反斜杠033
,请尝试更改它或删除它""
以使其取消反斜杠。
\033
应该是 ESC 字符(十进制 ASCII 27,八进制 033)。