2

If I run the following command at a bash prompt:

(for i in {1..100}; do echo $i; sleep 1; done) &

It will start counting and immediately return me to my prompt. I can continue working normally, but every second it will print a new number on top of whatever I'm working on. I can see the job in jobs and fg/kill it as expected.

Now, if I move this command into the following script, test.sh:

#!/usr/bin/bash
(for i in {1..100}; do echo $i; sleep 1; done) &

and I run ./test.sh, the same thing happens -- but the job no longer shows in jobs and I can no longer fg it. Why exactly is the second behavior so different from the first, and how would one go about controlling the second job (short of finding the PID and killing it that way)?

  • 1
    It's not in jobs because it did not originate from your (interactive) shell. I don't think you can "re-parent" a running process. – glenn jackman Dec 2 '15 at 22:11
2

You have to keep track of it's PID, which is put in $! for you, just for that purpose. E.g.,

#!/usr/bin/bash

(sleep 30; echo "slept for 30 seconds") &
sleeping_pid=$!
# do something
kill $sleeping_pid # or you can wait on it, or...

Note that $! is the most-recently started background job. So it does tend to get overwritten, hence why I copy it immediately to a different variable.

  • comment @derobert I'd add that you might need to use kill -TERM <pid> or kill -INT <pid> instead of just kill. I think ultimately it depends on the program running. For my own specific situation/OS this was necessary and hard to determine. – user1529413 Jun 25 '18 at 17:31
0

In my particular case, I was able to achieve my goal by changing the subshell within test.sh into a group command.

(for i in {1..100}; do echo $i; sleep 1; done) &

became

{ for i in {1..100}; do echo $i; sleep 1; done; } &

and then I was able to use all the job control functions. Luckily both the subshell and the group command are basically equivalent for my purposes, but they may not be for everybody.

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.