0

I know in bash I can print a colorful string, like:

echo -e "\033[33;1mhello\033[0m"

The output in a shell will be hello with golden color. But when I redirect the output to a file test.txt, the \033[33; will be in the text file too. However the grep --color=auto command won't redirect these characters into the text file. How can it do this?

Libin Wen
  • 434
  • 1
  • 5
  • 17
  • Sounds like a duplicate of http://stackoverflow.com/questions/911168/how-to-detect-if-my-shell-script-is-running-through-a-pipe – svante Sep 02 '13 at 08:19

3 Answers3

3

How about this?

#!/bin/bash

if [ -t 1 ]; then
    echo -e "\033[33;1mhello\033[0m"
else
    echo hello
fi

Here the explanation:

test -t <fd>, whose short form is [ -t <fd> ], checks if the descriptor <fd> is a terminal or not. Source: help test

wooghie
  • 437
  • 2
  • 8
1

It probably uses the isatty(3) library function on stdout file descriptor (i.e. 1). So use

if (isatty(STDOUT_FILENO)) {
   // enable auto colorization
}

in your C code.

In a shell script, use the tty(1) command:

if tty -s ; then
  # enable auto colorization
fi

or simply the -t test(1)

if [ -t 1 ]; then
  # enable auto colorization
fi
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • There are various scripts for removing color codes and all kinds of control chars, e.g. the one from this [question](http://unix.stackexchange.com/questions/14684/removing-control-chars-including-console-codes-colours-from-script-output). – scai Sep 02 '13 at 08:19
  • Thanks. I see. But that perl script doesn't work at least for Chinese words. The sed version may be better: http://www.commandlinefu.com/commands/view/3584/remove-color-codes-special-characters-with-sed – Libin Wen Sep 02 '13 at 08:35
  • The `--always` option should take an argument like "always" to force color regardless of the output destination. – chepner Sep 02 '13 at 13:12
0

Use the the GREP_COLORS variable with an export flag. Tested this and it works:

export GREP_COLORS='ms=01;33'
grep --color=auto -e hello
konsolebox
  • 72,135
  • 12
  • 99
  • 105