Comments on Linux pkill Command Tutorial for Beginners (5 Examples)
In Linux, if you need to kill a process (for whatever reason) through the command line, you can use the kill command, which requires you to pass as input the ID of the process you're trying to terminate. But did you know that there also exists a way to kill processes without specifying their PIDs?
2 Comment(s)
Comments
This is exactly what I was looking for.I am running motion with several ipcameras running to collect their respective motion detections and snaphots images. Sometimes I need to make changes to the their respective ipcam's conf files and have to stop/restart the motion daemon.
I needed to get the pkill pattern matching right so that it only saw and stopped the motion app and not the script which had the name "motion" in it.
The script I wrote is the following:
-----------------------------------
set -xv#!/bin/bash#---------------------# if no motion running then result = "1"# ps -ef |grep -i [m]otion# echo $?# 1# ps -ef |grep -i [m]otion## if motion is running then result = "0"# ps -ef |grep -i [m]otion# root 20046 1 0 17:10 ? 00:00:00 sudo motion# root 20047 20046 27 17:10 ? 00:00:02 motion# echo $?# 0#---------------------datesudo pkill -f "sudo motion"sleep 5 # wait five second before testing to see if motion has been stoppedps -ef |grep -i [m]otion |grep -i "[s]udo motion"OUT=$?echo "before while:" $OUTwhile [ $OUT -ne 0 ]do echo "" echo "...waiting for motion to restart..." echo "" date ps -ef |grep -i [m]otion |grep -i "[s]udo motion" OUT=$? echo "inside while:" $OUT sleep 5 # delay 5 seconds before testing againdoneecho ""dateecho ""echo "motion has been restarted successfully..."echo ""
-----------------------------------
Thank you very much for posting your examples.
I am facing the issue with pkill execution inside the bash script. It seems that pkill kills the whole process and next commands are not executed. Do you know what is going on there? Have a nice day.