0

I've been learning bash job control (e.g. here, here), but a simple example I made has confounded me:

rm tmp
for i in {1..30}; do 
   echo $i | tee -a tmp   #display counter and write it to log tmp
   sleep 1
done

If this is put in a script, and that script is run, then job control operations work as I'd expect and as I've read. For instance:

echo 'rm tmp; for i in {1..30}; do echo $i | tee -a tmp; sleep 1; done' > tmpscript.sh
chmod u+x tmpscript.sh
./tmpscript.sh
#start to see counting output
#now, type Ctrl z to suspend the script
#and verify the it's paused: 
tail tmp
#looks good, let's resume: 
fg
#and counting continues in the foreground

However, if the contents of tmpscript.sh are instead run at the command line, i.e. as rm tmp; for i in {1..30}; do echo $i | tee -a tmp; sleep 1; done, things get a little weird.

rm tmp; for i in {1..30}; do echo $i | tee -a tmp; sleep 1; done
#counting begins, so far so good
#now, type Ctrl z to suspend the script
#and verify the it's paused: 
tail tmp
#looks good, let's resume: 
fg
#the sleep command resumes, then it returns to the command prompt
#The rest of the for loop doesn't go, which we can verify: 
tail tmp

I interpret this as the suspend operation suspends whichever part of the command sequence is going on when you type Ctrl z, which is almost certainly the sleep. That makes sense. However, why is it that when you resume via fg, the rest of the sequence does not continue? My understanding is that it is because each command (in this case, sleep) counts as a single job. But, where does the rest go? Is there a way to suspend/continue (or do other job control operations on) the whole command sequence?

migrated from stackoverflow.com May 6 at 17:09

This question came from our site for professional and enthusiast programmers.

  • 1
    In an interactive shell, each command is a separate job. echo $i | tee -a tmp is one job, sleep 1 is another. The bash script is not an interactive shell, the entire script invocation is a single job to the original shell. – Barmar Apr 18 at 16:08

Your Answer

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

Browse other questions tagged or ask your own question.