Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

going through advanced bash scripting guide example 3.3 running a loop in background, i found this :

#!/bin/bash
# background-loop.sh
for i in 1 2 3 4 5 6 7 8 9 10 # First loop.
do
echo -n "$i "
done & # Run this loop in background.
# Will sometimes execute after second loop.
echo # This 'echo' sometimes will not display.
for i in 11 12 13 14 15 16 17 18 19 20 # Second loop.
do
echo -n "$i "
done
echo # This 'echo' sometimes will not display.
# ======================================================
# The expected output from the script:
# 1 2 3 4 5 6 7 8 9 10
# 11 12 13 14 15 16 17 18 19 20
# Sometimes, though, you get:
# 11 12 13 14 15 16 17 18 19 20
# 1 2 3 4 5 6 7 8 9 10 bozo $
# (The second 'echo' doesn't execute. Why?)
# Occasionally also:
# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# (The first 'echo' doesn't execute. Why?)
# Very rarely something like:
# 11 12 13 1 2 3 4 5 6 7 8 9 10 14 15 16 17 18 19 20
# The foreground loop preempts the background one.
exit 0

# Nasimuddin Ansari suggests adding sleep 1
#+ after the echo -n "$i" in lines 6 and 14,
#+ for some real fun.

i dont get this, does anybody understands this.

share|improve this question
1  
It is because of the threading: You put something in the background and something in foreground. But both of them echoes to the same "out". So there may be some mix-ups in the printing. You can solve this by adding sleep 1 after echoes. ;) –  mtndesign Dec 12 '12 at 8:06
add comment

1 Answer

up vote 2 down vote accepted

The background jobs execute asynchronously. That means that you are note able to predict the order of execution just by definition. Theoretically, even with adding sleep you may still encounter the issue: waiting just for some seconds does not eliminate the async nature of the bg jobs, the only thing you're actually doing is just lowering the probability of such mix-up.

share|improve this answer
    
thanks @Leonid and mtndesign for making things clear –  munish Dec 12 '12 at 10:59
    
You're welcome, munish! –  Leonid Dec 12 '12 at 12: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.