Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question
    
What do you mean by “without a pipe”? If no file name is specified, read from stdin. What more do you want? –  Gilles Jun 3 '12 at 22:51
    
My question started with 'Here is my question..", meaning if the user just ran the script on its own. So if data will never come through stdin, because it was never even invoked after a | in the first place. If that specifically is not possible, which I believe it may not be, checking for data would also suffice. basically i'd like the script to end and say, 'script needs a file name, or stdin', rather than just hanging with no output eternally as it now does. –  TechZilla Jun 3 '12 at 22:56

1 Answer 1

up vote 3 down vote accepted

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
share|improve this answer
    
I think I can take it from this point, thank you for your help. –  TechZilla Jul 3 '12 at 17:40

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.