Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

share|improve this question

3 Answers 3

up vote 3 down vote accepted

Perhaps with tput, check available colors count,

ncolors=$(tput colors)

if [[ $ncolors -ge 8 ]];then
   # colors available
fi
share|improve this answer
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

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).

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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