Terminal colors are produced through the use of
ansi escape codes, hidden markup characters inserted into the text that control how the terminal displays things.
grep, with the
--color option, inserts color codes into the output text stream whenever it finds a match.
tail, on the other hand, does not have that ability, so your only choice is to subsequently filter it through a program or script that does.
Note also that most programs that produce color output only do when the output is being sent directly to a terminal. When the output is being piped to a second program, or redirected into a file, colors are usually disabled, as the extra characters in the text are probably unwanted and can mess with subsequent operations.
But in
grep,
ls, and many other programs that produce color output, you can use
--color=always,
--color=auto, or
--color=never to control when the codes are inserted (auto the default behavior).
To see an example of the codes, try running:
Code:
echo "foo bar baz" | grep --color=always 'bar' >textfile
...and then view the file in a standard text editor. Assuming grep matched something You should see the markup characters embedded in the line, like this:
Code:
foo [01;31m[Kbar[m[K baz
But if you
cat the file back into the terminal, you'll see it turn red again.