Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Weird problem about "while" and "for" cycle statement in ksh 2

Status
Not open for further replies.

signalsys

Technical User
Sep 5, 2005
44
CN
Weird problem about "while" and "for" cycle statement in ksh

Some day i found a strange phenomenon when i use a loop structure in a ksh script:

(1) using "For" statement:
for i in `cat aaa`
> do
> rsh $i hostname
> done

And it returns the expected value:
P630_4
p630_1
P650_2

(2) using "while" statement:
cat aaa | while read i
> do
> rsh $i hostname
> done

It only returns the first value:
P630_4
it seems that the loop structure does not work when using "while" and there are "rsh" commands in the loop body.

Here supply the content of file aaa:
P630_4
P630_1
P650_2

Any suggestion about this problem ?
Thanks in advance.



 
That is because the first time you run an rsh in the loop, it 'eats away' all the stdin that's available, leaving nothing for the "while read" construct to read.

either disconnect the rsh from your standard input like so:

cat aaa | while read i
do
rsh $i hostname </dev/null
done

or use rsh -n to disallow reading from stdin for rsh like so:

cat aaa | while read i
do
rsh -n $i hostname
done


HTH,

p5wizard
 
Another option is to open aaa on a new filehandle and use the -u option of read to read from it.

Code:
exec 3< aaa
while read -u3 i
do
 rsh $i hostname
done

Rod Knowlton
IBM Certified Advanced Technical Expert pSeries and AIX 5L
CompTIA Linux+
CompTIA Security+

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top