1828578 Members
2856 Online
109982 Solutions
New Discussion

while read loop help

 
Avinash Agarkar
Valued Contributor

while read loop help

I have written a script using a loop but when I execute it using while read, it only read the first line and quits the loop after processing the first line. If I change it from (while read) to (for i in) it reads all the lines and finishes the loop?

any advice will be appreciated


Thanks,
Avinash
Great Power Comes With Great Responsibility
6 REPLIES 6
Michal Kapalka (mikap)
Honored Contributor

Re: while read loop help

hi,

the bets way is to send the loop that you are using.

mikap
Dennis Handly
Acclaimed Contributor

Re: while read loop help

This is the wrong forum for scripting.
What OS and shell are you using?
James R. Ferguson
Acclaimed Contributor

Re: while read loop help

Hi:

I would urge you to *post* your code. I suspect that you need two file descriptors --- one for the 'read' loop and another for the process you want to execute. If an 'ssh' or 'remsh' is called within the loop you will likely need to add the '-n' option to it.

Regards!

...JRF...

Matti_Kurkela
Honored Contributor

Re: while read loop help

Most likely you haven't noticed that the input/output redirection works a bit oddly in loop structures.

Wrong:

#!/bin/sh
# this reads only the first line
while read foo < inputfile.txt
do
echo "$foo"
done

Right:

#!/bin/sh
# this processes all lines in the file
while read foo
do
echo "$foo"
done < inputfile.txt

The "for i in $(cat inputfile.txt)" style loop is not suitable for files longer than the maximum command line length (8 KiB or so). If the file is longer than that, the script dies with "Command line too long" or equivalent error message.

With smaller files, it might work... but not the same as the "while read" loop: $i will iterate over the content of the input file, but one _word_ at a time, not one _line_ at a time.

MK
MK
Michael Steele_2
Honored Contributor

Re: while read loop help

HI

cat file | while read a (* or, number of words per line, a b c d e *)
do

echo $a (* whole line *)

done
Support Fatherhood - Stop Family Law
Sagar Sirdesai
Trusted Contributor

Re: while read loop help

Hi Avinash,
Please post the code which would help.

Sagar