66

I try to kill a process by pid file:

kill -9 $(cat /var/run/myProcess.pid)

The pid file contains the process number. However executing the kill gives me no stdout and the processes is still alive. But this works:

kill -9 PID

What is wrong with the first kill command? Does it fail to extract the PID from the file?

Example content of pid file:

5424

and

kill -9 5424

works.

DarkLeafyGreen
  • 69,338
  • 131
  • 383
  • 601

4 Answers4

89

I believe you are experiencing this because your default shell is dash (the debian almquist shell), but you are using bash syntax. You can specify bash in the shebang line with something like,

#!/usr/bin/env bash

Or, you could use the dash and bash compatible back-tick expression suggested by admdrew in the comments

kill -9 `cat /var/run/myProcess.pid`

Regardless, you can't rely on /bin/sh to be bash.

Community
  • 1
  • 1
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
84

In some situations, the more compact:

pkill -F /var/run/myProcess.pid

is the way to go. I've had trouble with the varieties:

kill $(cat /var/run/myProcess.pid)
# Or
kill `cat /var/run/myProcess.pid`

when I had to put the command into something else which might parse it using different rules, like Monit does for its start/stop commands.

jeteon
  • 3,471
  • 27
  • 40
4
cat /var/run/myProcess.pid | sudo xargs kill -9
ehsan houshmand
  • 373
  • 3
  • 6
  • 3
    While this may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – leopal Jan 23 '20 at 07:13
0

There is very simple method.

fuser -k /path/filename

example lets say you wanna kill apt lock file in linux.

sudo fuser -k /var/lib/dpkg/lock

and it will kill the process that holds the file.

Ry Van
  • 311
  • 2
  • 9