 
Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: March 18, 2024
The watch command provides options for displaying colors to make the text more readable.
In this tutorial, we’ll learn several ways to use those options. We’ll first consider the examples of watching various Linux commands. After that, we’ll look at the limitations of the watch command and consider a possible alternative.
To be able to watch the command while preserving any colors, we need to add the -c option by running the watch -c ‘<command>’.
Let’s look at this command in detail:
It’s important to put the command in single quotes as otherwise, some color codes may get mixed up.
For example, let’s consider watching the echo command with the ANSI codes to print Hello World in red color:
$ watch -c 'echo -e "\033[31mHello World\033[0m"'After running the above, we should be able to watch the Hello World text written in red.
For many commands, we should not only add the -c option, but also ensure specific color flags within the content remain. That’s because when we use watch, programs can detect they’re not writing to a terminal and could strip the color.
Let’s consider two examples where this is the case: the ls command, and the git diff command.
The ls command allows listing files and directories. To make its output color-formatted, we need to use the –color flag. So, the overall command would have two flags for coloring:
$ watch -c 'ls --color'Now, we should be able to watch the files and directories in a colored fashion.
Similarly, we should add the –color=always flag of the git diff command:
$ watch -c 'git diff --color=always'Here, the output of this command should be a colored version of the usual git diff command.
There can be times when a command doesn’t provide color flags. Let’s consider the pygmentize tool which specializes in printing file contents in color. It would be problematic to color-watch its output because it doesn’t provide the color flags we used above.
When there are no specific flags to preserve colors, we can avoid the watch command and replace it with the following while loop, which uses the terminal as its standard output:
$ while sleep <time>; do clear; <command>; doneHere, <time> is the time interval between the command runs, while <command> is the command we want to watch.
For example, to watch the pygmentize <file_to_print> command every second we need to run the following line:
$ while sleep 1; do clear; pygmentize <file_to_print>; doneThis shows the colored output of the pygmentize command every second.
In this article, we learned how to use the watch command to preserve the output colors. We firstly looked at the echo, the ls, and the git diff commands as examples. Finally, we learned an alternative to the watch command to avoid some of its color-flag limitations.