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*\K\d*(?=.*test.sh$)" | \
while read -r level
do kill $level
doneHowever, 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.
2 Answers
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.
Try
ps -aF | grep -Po "^\S{1,}\s*\K\d*(?=.*test.sh -x$)"