2

I have some color codes in my ~/.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

This adds some color to my man pages. However, when I use env, bash still interprets the color codes:

$ env | grep LESS
LESS_TERMCAP_mb=
LESS_TERMCAP_md=
LESS_TERMCAP_me=

Screenshot:

env colors

How can I escape these strings so I can see them as string literals? Ideally something like env | escape_color_codes_somehow.

2
  • 2
    You will never escape color codes in bash. They will haunt you forever... Commented Jun 8, 2018 at 14:09
  • 1
    cat -e (depending on your implementation of cat) will display a printable ASCII representation of otherwise unprintable characters.
    – chepner
    Commented Jun 8, 2018 at 15:51

1 Answer 1

2

You can do this:

[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] $

From 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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.