Reputation: 444
I know in bash I can print a colorful string, like:
echo -e "\033[33;1mhello\033[0m"
The output in a shell will be hello
with golden color. But when I redirect the output to a file test.txt
, the \033[33;
will be in the text file too. However the grep --color=auto
command won't redirect these characters into the text file. How can it do this?
Upvotes: 0
Views: 678
Reputation: 75478
Use the the GREP_COLORS variable with an export flag. Tested this and it works:
export GREP_COLORS='ms=01;33'
grep --color=auto -e hello
Upvotes: 0
Reputation: 1
It probably uses the isatty(3) library function on stdout file descriptor (i.e. 1). So use
if (isatty(STDOUT_FILENO)) {
// enable auto colorization
}
in your C code.
In a shell script, use the tty(1) command:
if tty -s ; then
# enable auto colorization
fi
or simply the -t
test(1)
if [ -t 1 ]; then
# enable auto colorization
fi
Upvotes: 1
Reputation: 437
How about this?
#!/bin/bash
if [ -t 1 ]; then
echo -e "\033[33;1mhello\033[0m"
else
echo hello
fi
Here the explanation:
test -t <fd>
, whose short form is [ -t <fd> ]
, checks if the descriptor <fd>
is a terminal or not. Source: help test
Upvotes: 3