Pkill with regex

killprocessregular expression

I have few java processes running like below,

java -jar /my/path/to/app/myapp.jar

java -jar /my/path/to/app/prodapp.jar

java -jar /my/path/to/app/testapp.jar

java -jar /my/path/to/app/myapp_v.01.jar

Now I can kill a particular process by pkill -f myapp.jar which is working as expected.
how do I kill myapp_v.01.jar using a regex, I tried pkill -f myapp_*.jar.
What is wrong with this regex ?

I am not looking for an alternative for pkill, I wanted to know why is the regex not working.

Best Answer

You need to understand the basics of regular expressions for this. The * modifier does not mean 'anything' as it is often assumed. The asterisk has this meaning in the shell but that's something different, not a regex. * means: take the previous character (or group of characters if preceeded by a [] group) and try to match it between zero and unlimited number of occurrences.

So what you're actually checking with myapp_*.jar is whether any of the following are present in the process list:

myapp.jar
myapp_.jar
myapp__.jar
myapp___.jar
...

See what I mean? It does not match 'myapp_v.01.jar' in any way. If you want to match any character, you're going to need .. So your regex for pkill could be: myapp_*.*.jar

Related Question