0

I have a problem with my while loops in bash. I read filenames from a file and I want to process them after that. The problem is that the while loop stops at the last line and without processing it which forces us to have an empty last line at that file ( which some tends to be deleted from time to time). Is there a way to loop an include the last line?

#datafile
filename1
filename2

while read project_name
do
 echo $project_name
done < "datafile"

this will print out filename1 but not 2.

BRG Anders Olme

5
  • Which version of bash are you using?
    – Decado
    Mar 24, 2011 at 7:41
  • The script above works as you expect on the systems I have to hand, both lines printed and no requirement for a blank last line.
    – user9517
    Mar 24, 2011 at 7:42
  • There's no filename2, but two filename1 :).
    – 3molo
    Mar 24, 2011 at 7:44
  • just to clarify, does it print filename1 twice or once without the newline?
    – Decado
    Mar 24, 2011 at 7:49
  • Using th default bash in ubuntu 10.10 (4.1). For me it prints filename1 only ( if I dont add an empty last line after filename2 )
    – Buzzzz
    Mar 24, 2011 at 11:07

2 Answers 2

4

The problem is that you have no newline at the end of file. As per this question on SO you should evaluate the exit code after the read execution. Better explanation in the link.

#!/bin/bash
DONE=false
until $DONE ;do
    read LINE || DONE=true
    echo $LINE
done < "datafile"
2
  • 1
    +1 (-0.1 for the lack of indentation) Mar 24, 2011 at 11:06
  • True. Indenting is important =) I'm going to edit the post. Mar 24, 2011 at 11:14
0

You should try this with for/cat to see if you see the same behavior:

for project_name in $(cat datafile)
do
  echo $project_name
done

However I can think of no reason why your original example wouldn't work too.

2
  • 1
    Using 'for' will cause problems if your filenames include spaces as it splits its input string on space. Using '"datafile" | while read VAR ' splits on newline, so is safe for use with filenames and paths.
    – Phil H
    Mar 24, 2011 at 9:50
  • well for splits the input string using the chars in the IFS variable, so you can change this variable temporarily so that for will split only on newlines.
    – stew
    Mar 24, 2011 at 11:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .