Thursday, May 9, 2024
1
rated 0 times [  1] [ 0]  / answers: 1 / hits: 1949  / 2 Years ago, sun, august 28, 2022, 10:07:19

I can run multiple instances of a bash script in the background and everything is great. I have it setup in such way that some have -x as a flag and some not. See:


./test.sh &
./test.sh &
./test.sh -x &
./test.sh -x &

Now, I want to kill all scripts that were run with the -x flag. I always kill scripts running in the background using this:


ps -aux | grep -Po "^S{1,}s*Kd*(?=.*test.sh$)" | 
while read -r level
do
kill $level
done

However, ps -aux doesn't show any arguments/flags that were given when the script was run. So when using that, I can't only grab the scripts that were run with -x. Is there a solution to this? I want to only kill the background scripts that were run with -x.


More From » command-line

 Answers
7

Use the pkill command with the -f flag.


The command pkill test.sh will kill all processes using test.sh as the command name. Using the -f flag is explained in man pgrep, as pgrep and pkill use similar syntax:



-f, --full


The pattern is normally only matched against the process name. When -f is set, the full command line is used.



However, you need to surround the search pattern with quotes, and escape the - of -x. So pkill -f "test.sh -x" will kill only the test.sh processes that run with the -x flag.


[#1394] Monday, August 29, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
oredoise

Total Points: 66
Total Questions: 116
Total Answers: 111

Location: Lebanon
Member since Sun, Aug 2, 2020
4 Years ago
oredoise questions
;