I want to write a shell script that will use colored output when output is terminal, and normal output when redirected to a file. How can I do that?
For utilizing the redirection of bash, execute any script, then define the > or >> operator followed by the file path to which the output should be redirected. “>>” operator is used for utilizing the command's output to a file, including the output to the file's current contents.
Redirecting output to append to a file When the notation > > filename is added to the end of a command, the output of the command is appended to the specified file name, rather than writing over any existing data. The >> symbol is known as the append redirection operator.
The '>' symbol is used for output (STDOUT) redirection. Here the output of command ls -al is re-directed to file “listings” instead of your screen.
Very simple:
if [ -t 1 ]; then
echo "Hello, terminal."
else
echo "Not a terminal."
fi
-t
tests if the given file descriptor (here, 1 = stdout) is attached to a terminal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With