So I have a small script that I run as source (for those interested, I do this so that I can attain the correct $SECONDS value of the person running the script), as well as place the program in the background. Inside of this script there is an infinite loop that runs to update a temp file every second.

So my question, how do I attain the PID of the loop inside the script that needs to be terminated to kill the updating of the temp file/the script?

  • In the second script, record the PID of the background process in a variable (e.g., pid=$!). Since you're using source, the variable will be visible in the first script.
    – larsks
    Aug 3, 2016 at 23:39

2 Answers 2

  1. If you source it, it's not really a separate script. It is as if you had all those lines you source present in the place/script you source/call it from.

  2. A loop doesn't have a PID. If it's in the foreground, it works under the current PID. But if you send it to the background, then the job get's it's own PID, which you can attain this way:

    do-something-in-a-loop & pid=$!

  3. You can also use the job spec of the task if you know it. If you have only 1 job, you can do kill %1.


The short answer is that the loop doesn't have its own PID since it doesn't run in a separate process, i.e. the PID of the loop is the PID of the script.

For a more useful answer, post actual code.

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.