0

I have simple Docker's command to kill database process:

docker exec  app-pgsql bash -c 'ps axuf |grep ils |cut -d" " -f3 |xargs kill -9 || :'

and as you can see, I'm looking for 3rd column from ps to get process ID but sometimes this column is different, one time 3rd, second time 4th, next time again 3rd, etc.
Is there any better solution to resolve this, no matter what's column will be?

Damian
  • 113
  • 2
  • 6
  • 1
    Rather than using `ps --> filter on process-name --> extract PID --> kill PID` use the dedicated utility [`pkill`](https://linux.die.net/man/1/pkill) that allows you simply send the desired kill signal directly to a process by **name** – HBruijn Aug 23 '19 at 07:27

1 Answers1

1

First and foremost: as @HBruijn said in the comment, use pkill, because using the method in your question is fragile, to say the least.

If you still want to stick with ps | filter_it | kill_it, I'll try to pinpoint some errors in the command you're trying to run. This may not answer your question, but it would be a bit too long to include it as a comment, so here we are.

First, I don't understand how the process ID could end up in different columns, for me, when I use ps axuf, the PID is in the second column. Maybe it is another version of ps you're using which have different defaults. You can control the output of ps with the -o switch, so if you use something like

ps -ho pid,command

then the PID will always be in the first column.

Second, if you use grep, you probably want to use a second grep -v as well. When piping commands, the shell will keep all processes alive. Since grep ils itself contains ils, it could very well end up in your final list. So if you use grep to filter, be sure to exclude grep itself, like this:

ps -ho pid,command | grep ils | grep -v grep

Third, using cut is a bad way of processing columnar texts, for if there are two delimiters, cut will treat the input as having an extra empty column, rendering the output ambiguous (kind of). Use something else, like awk.

So your final command should look like this:

ps -ho pid,command | grep ils | grep -v grep | awk '{print $1}' | xargs kill -9

In this case, instead of using awk, you could use cut (or really anything, e.g. sed), since the PID is guaranteed to be the first column, so cut would do. I rarely use cut and try to avoid it, hence, awk. :)

A final note: using kill -9 is usually considered as a "last resort". You should try to have a normal way of ending the process, since kill -9 will end the process no matter what, which can cause all kinds of funny effects, especially with databases.

Lacek
  • 6,585
  • 22
  • 28