Don't wait for "read line"

Hi

I am writing a bash script on Solaris, that should take n arguments, either appended to the script or taken as output from the last command (similar to grep). What I don't want is that the script waits for user input. In other words:

Possibility 1:

script.sh arg1 arg2 arg3 ...

Possibility 2:

ls | script.sh

If the script is executed without any arguments, a usage message is meant to appear. I know how to handle either one of the two possibilities:

Possibility 1:

while (($#)); do
    do_something $1
    shift
done

Possibility 2:

while read line; do
    do_something $line
done

But how would this be done in combination, so that the script does not wait for user input? I hope I made myself clear.

Thanks, Stefan

Hi.

Try this:

echo ARGS: $@
more 2>/dev/null | while read line; do
  echo $line
done

> ./Test
>

> echo a b c | ./Test
a b c

echo "a b c" | ./Test 1 2 3
ARGS: 1 2 3
a b c

I don't know if it's the best solution, but it seems to do the trick.

args=$#

while [ $# -gt 0 ]
do
  do_something "$1"
  shift
done

if [ $args -eq 0 ]
then
  while read line; do
    do_something "$line"
  done
fi

That was the other option, of course - unless there is nothing coming from stdout.

Hi all

Many thanks for your answers. As far as I understand the solution of cfajohnson, the script waits for input in the second while loop, if it is being called without any arguments (maybe I did something wrong?). However, the solution of scottn is doing exactly what I want. With that I can get a list of arguments either via appending them to the script or from stdout of the last command.

Thanks again.
Stefan