3

I have a shell function that colorizes a filename using tput.

color=$( tput setaf 1 )
normal=$( tput sgr0 )
colorize() {
    echo "${color}$1$(normal)"
}

When I call the function, the terminal displays the colorized filename as expected.

$ myScript.sh .
/path/to/dir # (in color red)

Then, if I redirect output to a file:

$ myScript.sh > /tmp/file.log

file.log still contains escapes sequences like:

^[[36m~/path/to/my/file/^[(B^[[[m

Could this be related to the TERM and infocomp, and how terminal interprets escape sequences?

The idea is to simulate a "non-display" terminal, isn't it?

My TERM is (Ubuntu 16.04):

$ echo $TERM
xterm

What should I do to prevent such tput escape sequences when my script is redirected to a file?

Workaround: add an option to my script to disable colorization manually, as in ls or grep like --color=none.

1 Answer 1

5

short: tput doesn't do that.

longer: your script can do that

For example, check if the standard output is a terminal:

if [ -t 1 ]
then
    color=$( tput setaf 1 )
    normal=$( tput sgr0 )
else
    color=""
    normal=""
fi
3
  • Thanks, works like a charm, and this even does not need to rewrite the echo command as you empty the color variables when not for a terminal output. Nice!
    – el-teedee
    Commented Feb 11, 2018 at 19:20
  • I am facing a problem with this technique. I have 2 .sh scripts, both using the technique, and both echoing colored output. The caller script successfully echoes colors, but the subscript does not, maybe because STDOUT is not redirected to a terminal but to a echo of my caller script. What to do to use this with subsripts ?
    – el-teedee
    Commented Feb 11, 2018 at 20:17
  • I solutionned the subscript problem by using: [[ -t 1 ]] && export coloredModed=1 in caller script, and if [[ -t 1 || $coloredMode = 1 ]] in subscript
    – el-teedee
    Commented Feb 11, 2018 at 20:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .