shell shell-script dash stdin – Check if Standard Input Comes from a File or Pipe in a Script

dashshellshell-scriptstdin

I know this has been poorly covered previously, but those answers either lack explanation or don't apply.

Basically at some point my scripts needs check if a file is specified, if it was it will be used later as input.

[ -f "$1" ] && TINPUT="$1"

simple enough… Now if a file was not found, or not specified, I would have TINPUT="-" which would tell the later command to read stdin.

Here is my question… How do i get the script to die with error, if it was run without a pipe or without a file specified?

I'm using dash, the Debian POSIX complient shell, so I can't use Bashisms. I also prefer to use lists, over ifs but most ifs could be written in lists anyway.

Best Answer

You can test whether standard input is a terminal:

if [ -n "$1" ]; then
  exec <"$1"
elif tty >/dev/null; then
  echo 1>&2 'Cowardly refusing to read data from a terminal.'
  exit 2
# else we're reading from a file or pipe
fi
Related Question