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:


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

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.


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 ]
    color=$( tput setaf 1 )
    normal=$( tput sgr0 )
| improve this answer | |
  • 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 Feb 11 '18 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 Feb 11 '18 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 Feb 11 '18 at 20:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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