0

I have a shell script that can read from a file or from standard input. Currently, if you don't give it a file or pipe text into it, it starts accepting input at the command prompt.

Instead, I would like to print "help" information in this scenario. Is there a standard way to do this? And if not, is there a way to detect standard input without affecting it? Or is there a way to detect where the would-be input is coming from?

I know that the read command can tell me whether there's input via its exit status. But it also acts on the input, affecting subsequent reads.

2

1 Answer 1

1

The solution is to check whether input is coming from a tty device. First, check whether args were given, then check tty.

if [ ! "$#" -gt 0 ] && tty -s ; then
  show_help
  exit 1
fi

From the documentation for tty:

Print the file name of the terminal connected to standard input.

If there isn't a terminal connected to standard input, tty gives a failure exit status. And the -s option suppresses output.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .