如果您愿意使用一组有限的、预先已知的颜色代码,则可以使用 Bash 参数扩展:
#!/usr/bin/env bash
# Define the variables containing ANSI color sequences.
RED="$(tput setaf 1)"
CYA="$(tput setaf 6)"
CLS="$(tput sgr0)"
# Sample input string
str='[String n${RED}â${CLS}m${CYA}è™${CLS}]'
# Replace the placeholders with their corresponding variable values.
str=${str//'${RED}'/${RED}}
str=${str//'${CYA}'/${CYA}}
str=${str//'${CLS}'/${CLS}}
# Output the result.
echo "$str"
这种方法利用了在 Bash 参数扩展中使用的参数本身会受到扩展的事实,除非单引号:
${<varName>//<search>/<replace>}
<search>
替换<replace>
变量值中的所有实例<varName>
。
'${RED}'
,例如, - 由于被单引号- 被视为文字搜索词。
${RED}
,例如 - 由于未引用-在用作替换术语之前被扩展,因此有效地用变量的值替换字面 量。${RED}
${RED}
封装在一个函数中:
printColored() {
local str=$1
local RED="$(tput setaf 1)" CYA="$(tput setaf 6)" CLS="$(tput sgr0)"
str=${str//'${RED}'/${RED}}
str=${str//'${CYA}'/${CYA}}
str=${str//'${CLS}'/${CLS}}
printf '%s\n' "$str"
}
printColored '[String n${RED}â${CLS}m${CYA}è™${CLS}]'
顺便说一句,我会重命名${CLS}
为${RST}
(用于“重置”)或类似的名称,因为“cls”一词建议清除整个屏幕。