How can I script an env-var containing ansi escapes without mucking up env terminal output?

StackOverflow https://stackoverflow.com/questions/19030589

Pregunta

Consider the following env exports from my .bashrc:

LESS_TERMCAP_mb=$(printf "\e[1;31m")
LESS_TERMCAP_md=$(printf "\e[1;31m")
LESS_TERMCAP_me=$(printf "\e[0m")
LESS_TERMCAP_se=$(printf "\e[0m")
LESS_TERMCAP_so=$(printf "\e[1;44;33m")
LESS_TERMCAP_ue=$(printf "\e[0m")
LESS_TERMCAP_us=$(printf "\e[1;32m")

This is fine and works as expected, but unfortunately when I dump env to the console it outputs the ansi colors and basically messes up the display of the terminal. I can pipe env to less to clean the ansi codes, but I was thinking that there is probably a better way to do this.

I created the following function which basically sets these variables inline before calling some terminal applications, but it doesnt set it for all applications.

less() {
    env \
    LESS_TERMCAP_mb=$(printf "\e[1;31m") \
    LESS_TERMCAP_md=$(printf "\e[1;31m") \
    LESS_TERMCAP_me=$(printf "\e[0m") \
    LESS_TERMCAP_se=$(printf "\e[0m") \
    LESS_TERMCAP_so=$(printf "\e[1;44;33m") \
    LESS_TERMCAP_ue=$(printf "\e[0m") \
    LESS_TERMCAP_us=$(printf "\e[1;32m") \
    less "$@"
}

Is there a better way, or any way, to script environment variables in such a way that they contain ANSI escape sequences but they dont evaluate when displayed via env?

¿Fue útil?

Solución

There's probably no way but instead of using env, use set instead:

> set | grep ^LESS_TERM
LESS_TERMCAP_mb=$'\E[1;31m'
LESS_TERMCAP_md=$'\E[1;31m'
LESS_TERMCAP_me=$'\E[0m'
LESS_TERMCAP_se=$'\E[0m'
LESS_TERMCAP_so=$'\E[1;44;33m'
LESS_TERMCAP_ue=$'\E[0m'
LESS_TERMCAP_us=$'\E[1;32m'

Another way is to explicitly change the characters:

> env | grep ^LESS_TERMCAP | sed 's|\x1b|ESC|g'
LESS_TERMCAP_mb=ESC[1;31m
LESS_TERMCAP_md=ESC[1;31m
LESS_TERMCAP_me=ESC[0m
LESS_TERMCAP_ue=ESC[0m
LESS_TERMCAP_us=ESC[1;32m
LESS_TERMCAP_so=ESC[1;44;33m
LESS_TERMCAP_se=ESC[0m
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top