Operating System - HP-UX
1757754 Members
2514 Online
108863 Solutions
New Discussion юеВ

Help with standard input to a script.

 
Russ Hancock_1
Frequent Advisor

Help with standard input to a script.

Hi People.

I have a requirement for a script that can handle a file that is piped in via standard input.
i.e cat inputfile | my_script
Once inside the script how can I reference the inputfile?
With normal inputs you can use $1 $2 etc, is there anything like that for piped input??

Cheers
Russ.
Russ
6 REPLIES 6
A. Clay Stephenson
Acclaimed Contributor

Re: Help with standard input to a script.

All you need to do is something like this:

while read X |
do
echo $X
# reads stdin 1 line at a time
done

If you would like split each line into $1, $2, ...

ARGS=$*
while read X |
do
set $X
# now $X has been split into $1, $2, ...
# $# is the number of vars
done

No points please, Clay
If it ain't broke, I can fix that.
Robin Wakefield
Honored Contributor

Re: Help with standard input to a script.

Hi Russ,

I would use an exported variable, which can then be read within your script:

FILE=inputfile
export FILE
cat $FILE | your_script

Rgds, Robin.
harry d brown jr
Honored Contributor

Re: Help with standard input to a script.

Russ,


while read w1 w2 w3 w4 w5 w6 w7 w8 w9 w10
do
echo $w1 $w2 $w3 $w4 $w5 $w6 $w7 $w8 $w9 $w10
done


live free or die
harry
Live Free or Die
Steven Sim Kok Leong
Honored Contributor

Re: Help with standard input to a script.

Hi,

I agree with Robin.

Had wanted to post exactly the same yesterday but was unable to due to forum connectivity issues with replying.

Hope this helps. Regards.

Steven Sim Kok Leong
Peter Kloetgen
Esteemed Contributor

Re: Help with standard input to a script.

Hi ,

why don't you simply change positions using command substitution:

your_script `cat input_file`

you use the standard input for the input file and you get a parameter list which you can use inside your script...

Allways stay on the bright side of life!

Peter
I'm learning here as well as helping
Kenny Chau
Trusted Contributor

Re: Help with standard input to a script.

Well, you can do it on this way:

# your_script inputfile

In your_script, you can add these lines:

while read field1 field2 field3
do
your_process
done < $1

This will read the lines from your inputfile and do the process that you want. If you inputfile had 7 fields, add up to field7 in the 'while' line.

Hope this helps.
Kenny.
Kenny