Re: SHELLdorado Newsletter 1/2005 - April 30th, 2005

From: Michael Tosch (eedmit_at_NO.eed.SPAM.ericsson.PLS.se)
Date: 05/02/05


Date: Mon, 02 May 2005 22:02:57 +0200

Stephane CHAZELAS wrote:
> 2005-04-30, 17:43(+02), Heiner Steven:
>
...
>> The following commands suppress this behaviour:
>>
>> file=/etc/motd
>> OIFS=$IFS; IFS= # Change input field separator
>> while read -r line
>> do
>> echo "$line"
>> done < "$file"
>> IFS=$OIFS # Restore old value
>
>
> This doesn't restore the previous value if IFS was previously
> unset.
>
> Also note that commands in the loop have their stdin affected.
>
> As other pointed out:
>
> while IFS= read -r line <&3; do
> printf '%s\n' "$line" # echo should be banished
> done 3< "$file"

Let me translate for the newcomers:

while IFS= read -r line; do
   echo "$line" # simple echo may remain
   read dummy
done < "$file"

has the problem that the 2nd read command reads from the same file as
the loop's read.
Your trick with reading from &3 (or higher) prevents that.

This leads to the following solution to the FAQ
Why does rsh (or remsh) disturbe a "while read" loop?

rsh (or remsh) "steals" some characters from stdin.

Preferred solution:

while IFS= read -r line <&3; do
   rsh remote-host "echo '$line'"
done 3< "$file"

The other solution is

while IFS= read -r line; do
   rsh -n remote-host "echo '$line'"
done < "$file"

-- 
Michael Tosch @ hp : com


Relevant Pages

  • Re: Regexes on the command line
    ... Useful for manipulating PATH, classpaths, etc. ... I always find it awkward when writing code to loop over all the entries in $PATH or something, because it's comma-separated - i usually send it to tr to make it space-separated, then loop over that, but IFS is a much better solution. ...
    (comp.lang.java.programmer)
  • Re: Empty Directory problem
    ... or it would fail with a file named ^J). ... > a loop (although there shouldn't be much difference since a loop ... IFS=" "; case $* in ...
    (comp.unix.shell)
  • RE: Error in Code
    ... without loop message before because of ifs and end ifs. ... Dim Heading1 As String ...
    (microsoft.public.excel.misc)
  • Re: nested loop
    ... inner loop, I run my program on file names in list2 as second argument ... I have m filenames in file1 and n in file 2. ... $ while IFS= read -r f1; ...
    (comp.unix.shell)
  • Re: testing if program is installed and version in .${SHELL}rc
    ... 2004-08-06, 09:40, Kevin Rodgers: ... IFS=: ... (commands is a zsh special associative array). ...
    (comp.unix.shell)