Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test stdout and stderr redirection in bash script

I would like to test in my bash script where stdout and stderr are directed, or more precisely, if they have been redirected.

Have you an idea ?

The $* bash variable don't give me this info.

like image 253
Sigmun Avatar asked Feb 18 '12 09:02

Sigmun


People also ask

How do I redirect both stderr and stdout to a file?

Redirecting stderr to stdout When saving the program's output to a file, it is quite common to redirect stderr to stdout so that you can have everything in a single file. > file redirect the stdout to file , and 2>&1 redirect the stderr to the current location of stdout .

What is stdout and stderr in bash?

stdout: Stands for standard output. The text output of a command is stored in the stdout stream. stderr: Stands for standard error. Whenever a command faces an error, the error message is stored in this stream.


1 Answers

Technically there is no way of telling whether stdin/stdout/stderr are "redirected" because you don't know what's invoking your script. If it's not being invoked from another shell, there is no concept of "redirection".

All you have to go on is what types the in/out/err file descriptors are (terminal, fifo, pipe, device, file etc). Normally you just want to detect whether your output is going to some user's screen or whether it's going to another process. In this case use [ -t 1 ] as per Mat's answer.

If you want to find out where/what your process has been redirected to, examine the targets of the symlinks /proc/$$/fd/1 and /proc/$$/fd/2.

Note that someone could connect the output of your process to a different terminal with ./myscript.sh > /dev/pts/1234. Then it would be "redirected", but stdout would still be a terminal.

Examples:

$ ls -l /proc/$$/fd/1 > results
$ bash -c 'ls -l /proc/$$/fd/1 >>results' > /dev/null
$ bash -c 'ls -l /proc/$$/fd/1 >>results' |cat 
$ bash -c 'ls -l /proc/$$/fd/1 >>results' > /dev/pts/0
$ cat results 
lrwx------ 1 je4d je4d 64 2012-02-17 21:09 /proc/2463/fd/1 -> /dev/pts/11
l-wx------ 1 je4d je4d 64 2012-02-18 13:17 /proc/8302/fd/1 -> /dev/null
l-wx------ 1 je4d je4d 64 2012-02-18 13:17 /proc/8304/fd/1 -> pipe:[222798]
l-wx------ 1 je4d je4d 64 2012-02-18 13:17 /proc/8307/fd/1 -> /dev/pts/0

[ -t 1 ] would be true for the 1st and 4th of those.

like image 81
je4d Avatar answered Oct 22 '22 16:10

je4d