I have put a command in a bash script to kill processes as below
#!/bin/bash
kill -9 $(ps ux | grep 'fluent' | awk '{print $2}')
As I run the script, e.g. ./mykill
, it has no effect
$ ps ux | grep fluent
ko 21690 0.0 0.0 112664 972 pts/3 S+ 15:28 0:00 grep --color=auto fluent
ko 26573 5.1 1.0 1743688 673592 ? Sl May14 836:08 /state/partition1/ans190/v190/fluent/cortex.19.0.0 -f fluent -cmd-port:35881:compute-0-4.local -workbench-session (fluent "3ddp -pshmem -host -alnamd64 -r19.0.0 -t16 -mpi=ibmmpi -path/state/partition1/ansys190/v190/fluent -ssh")
ko 26581 0.0 0.0 0 0 ? Z May14 0:00 [fluent] <defunct>
$
$
$ ~/mykill
Killed
$ ps ux | grep fluent
ko 21690 0.0 0.0 112664 972 pts/3 S+ 15:28 0:00 grep --color=auto fluent
ko 26573 5.1 1.0 1743688 673592 ? Sl May14 836:08 /state/partition1/ans190/v190/fluent/cortex.19.0.0 -f fluent -cmd-port:35881:compute-0-4.local -workbench-session (fluent "3ddp -pshmem -host -alnamd64 -r19.0.0 -t16 -mpi=ibmmpi -path/state/partition1/ansys190/v190/fluent -ssh")
ko 26581 0.0 0.0 0 0 ? Z May14 0:00 [fluent] <defunct>
However, if I run the command in the terminal, it will kill them.
$ kill -9 $(ps ux | grep 'fluent' | awk '{print $2}')
-bash: kill: (21899) - No such process
$ ps ux | grep fluent
ko 21915 0.0 0.0 112664 972 pts/3 S+ 15:31 0:00 grep --color=auto fluent
What is the reason then?
pkill
instead. – Kusalananda May 25 '19 at 19:44pkill
is also incomplete. Because I have to kill multiple process names. for example,pkill fluent
,pkill cortex
and others. That command will kill all things. – mahmood May 25 '19 at 19:45kill -9
. This is usually not a good idea in the general case. It's a related question. – Kusalananda May 25 '19 at 19:46pkill -f
. – Kusalananda May 25 '19 at 19:46defunct
processes and I thinkkill -9
is the best at the moment. – mahmood May 25 '19 at 19:47ps
, thegrep
may be killed before other processes, which is why it's always better to usepkill
. – Kusalananda May 25 '19 at 19:56grep
should be dead and reaped by the time thekill
runs. The danger is that its PID could be already reused for another innocent process. But yes,kill $(ps ...)
sucks, doubly so because of the pretentiousgrep | awk
mannerism. – May 25 '19 at 21:05~/mykill
and./mykill
is just a typo? you're not running a different script than the one you're showing? – May 25 '19 at 21:14~/
and./
are the same. – mahmood May 26 '19 at 20:40pkill
instead. – May 26 '19 at 22:18