Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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

share|improve this question
    
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. –  Iain 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
add comment

2 Answers

up vote 4 down vote accepted

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"
share|improve this answer
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
add comment

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.

share|improve this answer
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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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