我的 ~/.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 | 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 (!
), andparameter
is not a nameref, it introduces a level of variable indirection. Bash uses the value of the variable formed from the rest ofparameter
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 ofparameter
itself. This is known as indirect expansion. Ifparameter
is a nameref, this expands to the name of the variable referenced byparameter
instead of performing the complete indirect expansion. The exceptions to this are the expansions of${!prefix*}
and${!name[@]}
described below.<强>
${!prefix*}
<强>${!prefix@}
block 引用>Names matching
prefix
. Expands to the names of variables whose names begin withprefix
, separated by the first character of theIFS
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/