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

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$)"