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?


while read project_name
 echo $project_name
done < "datafile"

this will print out filename1 but not 2.

BRG Anders Olme

  • Which version of bash are you using? – Decado Mar 24 '11 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 '11 at 7:42
  • There's no filename2, but two filename1 :). – 3molo Mar 24 '11 at 7:44
  • just to clarify, does it print filename1 twice or once without the newline? – Decado Mar 24 '11 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 '11 at 11:07

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.

until $DONE ;do
    read LINE || DONE=true
    echo $LINE
done < "datafile"
  • 1
    +1 (-0.1 for the lack of indentation) – Dennis Williamson Mar 24 '11 at 11:06
  • True. Indenting is important =) I'm going to edit the post. – David Costa Mar 24 '11 at 11:14

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

for project_name in $(cat datafile)
  echo $project_name

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

  • 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 '11 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 '11 at 11:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.