A.Razavi
A.Razavi

Reputation: 509

How to stop a nohup job that is using for loop in bash?

I have a nohup job that is running in background. It has a for loop that will repeat a task for 10 times. I have to use "kill " 10 times to stop it completely. Is there a more efficient way to do this?

Upvotes: 1

Views: 15506

Answers (3)

nbari
nbari

Reputation: 26985

You could use a mix of pgrep and pkill.

To find all your process matching your script this could be used:

pgrep -fl command

The -f will match against full argument list, and the -l stands from long output. To kill all the does process:

pkill -f command

To kill only the children process, once you find the parent PID you could try:

pkill -9 -P <parent pid>

This will send signal 9 kill to all processes with a parent process ID -P <parent pid>

To kill all the parent/child you could use:

kill -9 -PID

Notice the - on the PID, it means to send the signal to the PID and all its child processes.

Upvotes: 3

Adam Katz
Adam Katz

Reputation: 16236

The $! variable stores the process number of the most recently backgrounded job.

#!/bin/sh
for i in 1 2 3 4 5 6 7 8 9 10; do
  nohup sleep 300 &
  CMD_LIST="$CMD_LIST $!"
done
kill $CMD_LIST

This launches ten backgrounded commands that will each take five minutes (300 seconds). It stores their process IDs in $CMD_LIST. After the loop, it kills them all. Note the intentional lack of quotes in the kill command (each item in the list is a separate argument).

Upvotes: 0

downtheroad
downtheroad

Reputation: 419

what if you:

ps -ef|grep <script name>

get PID (second column)

then:

kill -9 <script PID>

Upvotes: 5

Related Questions