I started a while loop as follows:
while true; do {command}; sleep 180; done &
Notice the &
.
I thought when I killed the terminal, this while loop would stop. But it is still going. It has been hours since I killed the terminal session.
How do I stop this while loop?
I started
and closed the terminal to test it, now I got the same problem.
If you already closed the terminal you've started the loop in
Let's get an overview of running processes with
ps fjx
, the last lines on my machine readYou can see
yad
as a subprocess of/bin/bash
, if I closeyad
it changes tosleep 60
in the output ofps
. If the tree view is too confusing you can also search the output as follows1:The output lines begin with two numbers, the first being the PPID, the process ID of the parent process and the second being the PID, the ID of the process itself. It's because of that
9411
appears in both rows here:That's the
bash
subshell we want to kill and we just found out its PID, so now everything that remains is a simpleand the annoying subshell is gone for good.
1: The notation as
grep "[y]ad"
instead of simplygrep yad
prevents thegrep
process itself from showing up in the results list.If you have the terminal still open
bash
provides the variable$!
, which “expands to the process ID of the job most recently placed into the background”, so the following just kills the latest process in the background:If it's not the latest process, just can get a list of running jobs with the
jobs
builtin, example output:There are two jobs in the job list, to kill one of them you can access it with the job number or the shortcuts
%
,%+
(“current job”) and%-
(“previous job”), e.g. to kill the loop running in the background you could doand to kill the suspended
sleep 10
job:I need to note that when you close the terminal where you entered that command, the sub-command should've died along with it. Trying to reproduce this showed this behavior.
Now, assuming that you indeed are in a situation where this didn't happen, one way to go about killing the program you left running in the background, which was caused by the
&
at the end of the command, is as follows:echo $$
to note your current PID (process ID), so that you don't kill your own session.ps -ef | grep $SHELL
command to find which programs are running a shell.echo $$
result above; this is the PID you want to kill.kill -SIGTERM <pid>
command, where<pid>
is the numeric value you identified in step #3You could also restart your session or your computer, but the above will allow you to avoid that.
The
&
will make the terminal create a new process and get your code to run inside it. So your code becomes independent from the terminal process. Even if you close the terminal the newly process in which your code is running won't stop. So either remove&
or dops -aux
, locate your process and kill itkill (process id)
.