10

Possible Duplicate:
Colors with unix command “watch”?

In one of my programs, I want to use colored text as output, so I am using ANSI escape sequences for that, e.g. like this:

echo -e '\033[34mHello World\033[0m'

It prints "Hello World" in blue color. (actually it is a Python program using "print", but that does not matter for the question)

Now I want to repeat execution of the program using the bash program "watch". But when I execute the very same line as above using "watch", i.e.

watch echo -e '\033[34mHello World\033[0m'

the text is not blue, and the output becomes "-e 033[34mHello World033[0m". So the ANSI escape sequences are not decoded somehow.

Is there a way to make the program "watch" respect the escape sequences, or is there an alternative to "watch" to obtain the same effect?

It is ok if it only works on Linux as I am only using that.

Update: So one solution would be to install a newer version of "watch" that knows the --color option. But is there any other way, maybe a similar program to "watch"? (I am not the admin of that machine.)

Community
  • 1
  • 1
proggy
  • 847
  • 2
  • 9
  • 17

2 Answers2

14

The --color option does the trick for me.

watch --color -n 1 "echo -e '\033[36mHello World\033[0m'"

Or, in the absence of the color option, how about a home-grown watch:

while [ 1 ]; do clear; echo -e '\033[36mHello World\033[0m'; sleep 1; done
ddoxey
  • 2,013
  • 1
  • 18
  • 25
  • Yeah, thank you, but I just found out I have an old version of "watch" without the --color option. But it would indeed be the solution to the problem. – proggy Nov 30 '12 at 05:35
  • Aha. I thought that was too easy. – ddoxey Nov 30 '12 at 05:36
  • Hmm your second solution is not ideal because it flashes the screen which is a little bit nasty (my program takes some time before it shows the results). But still your answer is very much appreciated. – proggy Nov 30 '12 at 05:49
  • 1
    Ah, but if I cache the results of my program before I clear the screen, I obtain the desired effect: - while [ 1 ]; do a=$(execute_whatever); clear; echo $a; sleep 2; done - I think that works for me, I just wrap it in a little script (cwatch?) and that's it :) – proggy Nov 30 '12 at 05:53
6

Based on ddoxey's answer, I wrote a small script "cwatch" which solves my problem for the moment:

#!/bin/bash
# do something similar to "watch", but enable ANSI escape sequences for colors
# obsolete if new version of "watch" is available which has the --color option
# 2012-11-30

while [ 1 ]
do
  output=$(eval $@)
  clear
  echo -e "$output"
  sleep 2
done

I could still add a "--delay" option...

proggy
  • 847
  • 2
  • 9
  • 17