Bash脚本打印包含在变量中的转义序列

Rob*_*ino 6 bash

Bash代码:

yellow="\e[1;33m"
chosen_colour="${yellow}"
declare -i score=300
printf '%s %d\n' "${chosen_colour}" "${score}"
Run Code Online (Sandbox Code Playgroud)

结果:

\e[1;33m 300
Run Code Online (Sandbox Code Playgroud)

应该:

300 /* in yellow */
Run Code Online (Sandbox Code Playgroud)

如何在不使用以下任何一种语法的情况下将包含ANSI转义序列的字符串值插入到printf语句中:

避免1 :(实际上是有效的,但是做很多事情都很浪费+=)

s="${yellow}"
s+="${score}"
s+=...
s+=...
s+=...
s+=...
s+=...
s+=...
s+=...
s+=...
Run Code Online (Sandbox Code Playgroud)

避免2 :(在我的情况下很难做到需要这个构造的绝对数量的变量)

printf "${yellow}${score}${a1}${a2}${a3}${a4}${a5}${a6}${a7}${a8}........."
Run Code Online (Sandbox Code Playgroud)

我希望能够根据预定义的FORMAT字符串传递要替换的值,使用调用的参数部分printf,正如我在第一个示例中所做的那样.

我可以忍受这样的事情:

printf \
  '%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s...' \
    "${a1}" \
    "${a2}" \
    "${a3}" \
    "${a4}" \
    "${a5}" \
    "${a6}" \
    ...
Run Code Online (Sandbox Code Playgroud)

虽然最终,对于我的许多变量,我会使用这样的结构:

${!a*} # or similar
Run Code Online (Sandbox Code Playgroud)

per*_*eal 4

你做:

printf "^[%s foo" "${a1}" # that is ctrl+v, ESC, followed by %s
Run Code Online (Sandbox Code Playgroud)

或者:

printf "\033%s foo" "${a1}"  # 033 octal for ESC
Run Code Online (Sandbox Code Playgroud)