BSalunke
BSalunke

Reputation: 11737

How to kill a running for loop on linux?

I'm working on Linux, I have executed the for loop on a Linux terminal as follows:

for i in `cat fileName.txt`
do
echo $i
vim $i
done

fileName.txt is a file contains the large no of file entries that I'm opening in vim editor one by one. Now i have to skip opening other files in between.(i.e. i have to break the for loop). Any suggestion how to get the PID of running for loop? and kill the same. Thanks in advance.

Upvotes: 8

Views: 17010

Answers (4)

chab42
chab42

Reputation: 36

To terminate the creation of the vim processes, you must stop the for loop. This loop is managed by a bash process. So find the PID of the process and kill it. To do so, find the PPID of a vim process, which is the PID of its parent process, and terminate the parent process : ps -elf | tr -s ' ' | grep vim | cut -f5 -d ' ' | xargs kill

You can use this command with this second one, which will kill all vim processes, to ensure no vim instances remain: ps -elf | tr -s ' ' | grep vim | cut -f4 -d ' ' | xargs kill

I see that you had a problem with "permission not permitted". This might be caused by a lack of permission, so to be sure it will kill the processes, you can call xargs kill with sudo : ps -elf | tr -s ' ' | grep vim | cut -f5 -d ' ' | sudo xargs kill

Upvotes: 0

eepp
eepp

Reputation: 7585

You want to kill the running job. Press CtrlZ. Bash will show something like:

[1]+  Stopped                 vim $i

Use that number with kill to send the KILL signal:

kill -9 %1

and it should be killed afterwards:

[1]+  Killed                  vim $i

Upvotes: 15

sneak
sneak

Reputation: 1108

Find the process id (PID) of the parent of the vim process, which should be the shell executing the for loop. Try using "pstree -p". Then, kill that process id using "kill ".

Upvotes: 2

Thomas
Thomas

Reputation: 182000

This might also do the trick:

while true ; do killall vim ; done

You can abort this one with ^C as usual.

Upvotes: 2

Related Questions