Bash

有顏色程式碼時如何使用 printf 和 %s?

  • March 16, 2021

我有這些行:

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’s 之外,還有更好的方法來命名字元串嗎?

細節 - 顏色是這樣定義的:

fail_color="\033[31;1m"
pass_color="\033[32;1m"
color_end="\033[0m"

我喜歡賽勒斯的回答,但這種語法也適用:

#!/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 說“一切看起來都不錯!”。:)

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)-release)、RHEL 7.0 (bash 4.3.11(1)-release) 和 Solaris 11 (bash 4.1.9(1)-release)

引用自:https://unix.stackexchange.com/questions/205497