1

I want to do something like this in my linux box:

if [[ colors exist ]];then
echo "some text in colors"
fi

my doubt is :

i am using sed to put colors in log file for some text but if the linux box does not have colors enabled will it modify the log file in unneccsasy way like putting some unnecessary characters like [033m etc

3

Perhaps with tput, check available colors count,

ncolors=$(tput colors)

if [[ $ncolors -ge 8 ]];then
   # colors available
fi
  • 1
    Since tput only checks the $TERM variable, it'll fail to detect if using the program in a pipeline. Standard practice tends to be to check if stdout is a TTY as well: tty(1) is your friend. Something like if tty >/dev/null 2>/dev/null && [[ $(tput colors) -ge 8 ]]; then ... would work well. – Alexios Mar 25 '13 at 11:08
  • if [[ $ncolors -gt 2 && $ncolors -lt 8 ]]; then what?; fi – l0b0 Mar 25 '13 at 15:26
1

The tty colors are a characteristic of the terminal on which the text is shown. Almost all terminals today handle the ANSI escape sequence, so you can get away with colorizing the text when generated, but you should really do it when it is written (perhaps under the control of the user at the writing end). E.g. set up custom coloring for your text for your pager).

0

A possible method of detecting whether you are running directly from a terminal emulator, or if the output is being written to a log file instead, is to use readlink:

if [[ $(readlink -f /dev/stdout) =~ '^/dev/pts/' ]]; then
   # colors available
fi

This should normally work on modern linux with udev and procfs. I'm not sure if something more portable exists. This uses the special bash regular expression operator =~, so it will only work with bash.

An alternative is, as somebody else already explained, to use tty >/dev/null; in your case though, you may only be interested in standard output and not standard input, so you'll want to make your standard output the standard input of tty:

if tty <&1 >/dev/null; then
   # colors available
fi

This would disable colors when you run ./myscript.sh >>log_file, but enable them when you run ./myscript.sh.

I'd recommend using [[ $(tput colors) -ge 8 ]] as well, so that when the environment variable TERM is set to dumb, colors won't be output.

If you do write a log file with colors in it, you can still read it; you'll have to use something like less -r or multitail -cT ansi from a terminal emulator with color support though.

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.