Search code examples
posixsh

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


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...?


Solution

  • 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