bash - 如何在 Bash 中转义颜色代码?

标签 bash ansi-colors

我的 ~/.bashrc 中有一些颜色代码:

export LESS_TERMCAP_mb=$'\E[01;31m'       # begin blinking
export LESS_TERMCAP_md=$'\E[01;38;5;74m'  # begin bold
export LESS_TERMCAP_me=$'\E[0m'           # end mode

这为我的手册页增添了一些色彩。但是,当我使用 env 时,bash 仍然解释颜色代码:

$ env | grep LESS
LESS_TERMCAP_mb=
LESS_TERMCAP_md=
LESS_TERMCAP_me=

屏幕截图:

env colors

如何转义这些字符串以便可以将它们视为字符串文字?理想情况下类似于 env | escape_color_codes_somehow

最佳答案

你可以这样做:

[STEP 101] $ echo ${!LESS_*}
LESS_TERMCAP_mb LESS_TERMCAP_md LESS_TERMCAP_me LESS_TERMCAP_se LESS_TERMCAP_so LESS_TERMCAP_ue LESS_TERMCAP_us
[STEP 102] $ for varname in ${!LESS_*}; do \
                 printf '%s=%q\n' $varname "${!varname}"; \
             done
LESS_TERMCAP_mb=$'\E[01;31m'
LESS_TERMCAP_md=$'\E[01;37m'
LESS_TERMCAP_me=$'\E[0m'
LESS_TERMCAP_se=$'\E[0m'
LESS_TERMCAP_so=$'\E[01;44;33m'
LESS_TERMCAP_ue=$'\E[0m'
LESS_TERMCAP_us=$'\E[00;32m'
[STEP 103] $

来自bash manual :

${parameter}

If the first character of parameter is an exclamation point (!), and parameter is not a nameref, it introduces a level of variable indirection. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion. If parameter is a nameref, this expands to the name of the variable referenced by parameter instead of performing the complete indirect expansion. The exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below.

<强> ${!prefix*}
<强> ${!prefix@}

Names matching prefix. Expands to the names of variables whose names begin with prefix, separated by the first character of the IFS special variable. When @ is used and the expansion appears within double quotes, each variable name expands to a separate word.

关于bash - 如何在 Bash 中转义颜色代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50762472/

相关文章:

bash - 自定义 cd 命令

python - 包含在自己的字符串中的干净字符串列表

emacs 去掉了 shell 中的所有 ansi 颜色代码

plugins - 如何在Jenkins中使用ANSIcolor插件?

html - 从 html 将颜色渲染到命令行?

linux - 按编号顺序创建第一个不存在的文件

bash - 使用 bash 自动回答 Graphite 安装的 django sync 提示

linux - 以下 "top"命令: top -p `pgrep process-name | tr "\\n" "," | sed 's/,$//' `的语法简单解释是什么

vim - VIM 中的 ANSI 颜色代码

ruby - 如何在 Ruby 中为字符串设置颜色