[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Reading input piped to a bash script



On Monday 18 October 2004 22.07, Sergio Basurto wrote:
> > Can anyone explain how I can read input to a bash
> > script through a pipe?
>
> You should use exec like the following simple example:
>
> #!/bin/bash
>
> exec 6<&0       # Link file descriptor #6 with stdin.
>
> read a1         # read if somethign comes from a pipe
>
> echo $a1        # print the output of the pipe.
>
> # you can make here the validation that you need if not
> then read $1
> case a1
> .
> esac
>
> exec 0<&6 6<&-  # restore stdin.

Hmm.. this doesn't seem to solve my problem because "read a1" will wait 
for some input even if there is none. What I want is for the script to 
*check* if there is any input being piped to the script, and if there 
isn't then check the first parameter to the script. However, I am 
starting to think that that is not possible. Maybe you have to do it the 
other way around, check for a parameter first, and then simply assume 
there is something on stdin. This works like that:

if [ $# == 0 ]
then
    piped=`cat`
    echo "From pipe: $piped"
else
    echo "From parameter: $1"
fi

The problem here is that if I don't provide any parameter to the script, 
and I don't pipe anything to it, it prompts the user for input. What I 
would like is an error message saying "wrong number of parameters" or 
something. Is there a solution to my problem?

Thanks
Olle



Reply to: