Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a bash script, how can I tell if the script output is redirected to a file?

Tags:

linux

bash

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?

like image 951
Eran Ben-Natan Avatar asked Feb 04 '15 07:02

Eran Ben-Natan


People also ask

How do I redirect a output to a file in bash?

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.

Which character redirects output to a file?

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.

Which command displays output on screen as well redirects output to other file?

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.


1 Answers

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.

like image 164
nneonneo Avatar answered Oct 28 '22 06:10

nneonneo