Mic*_*ant 6 bash shell-script printf
我有这些行:
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
Run Code Online (Sandbox Code Playgroud)
这工作正常,并为我提供了预期的输出 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".
Run Code Online (Sandbox Code Playgroud)
所以我试着把它改成
printf "%s Error - Function: %s, Line: %s \n", "$fail_color", "$function", "$line_number"
Run Code Online (Sandbox Code Playgroud)
但现在输出显示颜色代码详细信息而不是颜色:
\033[31;1m, Error - Function: words,, Line: 94
,do_test: Third parameter missing - expected result
Run Code Online (Sandbox Code Playgroud)
相关 - 有没有更好的方法来命名除 multiple 之外的字符串%s
?
细节 - 颜色是这样定义的:
fail_color="\033[31;1m"
pass_color="\033[32;1m"
color_end="\033[0m"
Run Code Online (Sandbox Code Playgroud)
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"
Run Code Online (Sandbox Code Playgroud)
输出:
错误 - 函数: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)-release)、RHEL 7.0 (bash 4.3.11(1)-release) 和 Solaris 11 (bash 4.1.9(1)-release)
我喜欢赛勒斯的答案,但这种语法也有效:
#!/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"
Run Code Online (Sandbox Code Playgroud)
ShellCheck 说“一切看起来都不错!”。:)