How to check if stdin is from the terminal or a pipe in a shell script?

l0b0 picture l0b0 · Mar 16, 2010 · Viewed 17.8k times · Source

I am writing a POSIX shell script that may or may not receive input from stdin as in foo.sh < test.txt, non-interactively.

How do I check whether there is anything on stdin, to avoid halting on while read -r line...?

Answer

dmedvinsky picture dmedvinsky · Mar 16, 2010

If I get the question right, you may try the following:

#!/bin/sh
if [ -t 0 ]; then
    echo running interactivelly
else
    while read -r line ; do
        echo $line
    done
fi