Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

The following test script has a problem. When I add the line (sleep 5 ) & in the script then the "while read" loop does not read all lines from the file, but only prints the first line.

But when I remove the ( sleep 5 ) & from the script, then the script prints all lines as defined in the file.

Why the ( sleep 5 ) & causes this?

And how to solve the problem? I want to create a new process (for which the sleep is just an example) in the while loop:

$ more test 
#!/bin/ksh  
while read -r line ; do
    echo Read a line:
    echo $line

    ( sleep 5 )&
    RESULT=$!
    echo Started background sleep with process id $RESULT

    sleep 1
    echo Slept for a second

    kill $RESULT 
    echo Killed background sleep with process id $RESULT
done < file
echo Completed 

On my Linux, when using the following contents of file:

$ more file 
123 aaa 
234 bbb 
556 ccc

...running ./test just gives me:

Read a line:
123 aaa
Started background sleep with process id 4181
Slept for a second 
Killed background sleep with process id 4181
Completed
share|improve this question
2  
You've been asked several time to properly format your posts. Use the 101010 button or indent each line of code four spaces, please. Also, you need to mark some answers as accepted. –  Dennis Williamson Jun 20 '10 at 14:38
2  
It works just fine for me. –  Dennis Williamson Jun 20 '10 at 14:40
3  
I just rolled back your editing again Yael, don't rollback edits made by others if it improves formatting. It's considered rude, stubborn and childish. If you don't like people editing your posts, this site may not be for you. –  BloodPhilia Jun 20 '10 at 14:43
1  
I'm seeing quite some things that you should avoid when using this website anyway. Like double commenting the same thing, not accepting answers (You've got a 0% accept rate, this will demotivate others to answer your questions), ignoring edits... This website is community maintained and therefore needs the input of everyone. Accepting answers and comments from others helps you do just that! ;) –  BloodPhilia Jun 20 '10 at 15:19
1  
Does yours? You're not giving us that information... :-( (Like I wrote: I tested on a Mac, which has KSH built-in as well.) –  Arjan Jun 20 '10 at 15:58

1 Answer 1

From the Ksh changelog for ksh93s:

06-10-23 A bug in which the value of $! was affected by a background job started from a subshell has been fixed.

If your version of ksh is older than that (you should mention the version in your question!), you might be observing this bug.

share|improve this answer

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.