Score:0

How to kill a script running in the background, but only get the PID of the script when it was run with a certain flag

in flag
Cas

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
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.

Score:1
bd flag

Try

ps -aF | grep -Po "^\S{1,}\s*\K\d*(?=.*test.sh -x$)"
Score:1
uz flag
Jos

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.

hr flag
... or use the `--` end-of-options flag `pkill -f -- "test.sh -x"` ... you could also use pattern `"test.sh[ \t]+-x"` to allow for arbitrary horizontal whitespace
uz flag
Jos
Good point @steeldriver. I always manage to forget about `--`.
hr flag
... when you think about it, it's kind of odd that `pgrep`/`pkill` don't implement the `-e pattern` thing that regular grep has to disambiguate the pattern from the options
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.