Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Colors with unix command "watch"? [closed]

People also ask

What is watch in Linux command?

The watch command is a built-in Linux utility used for running user-defined commands at regular intervals. It temporarily clears all the terminal content and displays the output of the attached command, along with the current system date and time. By default, the watch command updates the output every two seconds.

How do you escape the watch command?

To exit the watch command, we press Ctrl-C.

How do I see colors in terminal?

Your problem is that most probably colored output is disabled in your terminal. Then go in your Terminal settings -> Preferences -> Profiles -> Text -> Display ANSI colors. Open a new terminal and you should be ready to go!


Some newer versions of watch now support color.

For example watch --color ls -ahl --color.

Related.


Do not use watch ... When you use watch programs can detect they're not writing to a terminal and then strip the color. You must use specific program flags to keep the control codes there.

If you don't know the flags or there isn't you can make a poor's man watch by:

while sleep <time>; do clear; <command>; done

It will have a bit of flicker (watch works "double buffered") but for some stuff it is useful enough.

You may be tempted to make a double buffered poor man's watch using

while sleep <time>; do <command> > /tmp/file; clear; cat /tmp/file; done

But then you'll hit again the "I am not writing to a terminal" feature.


You can duplicate the fundamental, no-frills operation of watch in a couple lines of shell script.

$ cat cheapwatch 
#!/bin/sh

# Not quite your Rolex

while true ; do
  clear
  printf "[%s] Output of %s:\n" "$(date)" "$*"
  # "$@" <- we don't want to do it this way, just this:
  ${SHELL-/bin/sh} -c "$*"
  sleep 1  # genuine Quartz movement
done

$ ./cheapwatch ls --color  # no problem

Eventually, someone very clever will hack a tr command into this script which strips control characters, and then force the user to use --color to disable that logic. For the time being, the sheer naivete of this implementation is keeping the color-eating monster away.

If you're in a situation where watch doesn't have the --color option and you can't upgrade the package for whatever reason, maybe you can throw this in.


While other answers solve this problem, the easiest way to accomplish this is using the unbuffer tool. To use it simply do:

$ watch --color 'unbuffer <your-program>'

This way you don't have to hunt for control sequence enabling flags of your program. The caveat however is that your version of watch should support the --color flag.

You can install unbuffer on Debian or Ubuntu using sudo apt-get install expect.