1

I'm running 3 apps with the same file name from different paths:

$ ~/app1/main

$ ~/app2/main

$ ~/app3/main

I want to create a bash script which accepts the full name to an executable file and kills that app.

 $ ./my_killer.sh /home/me/app2/main

How can I do that, particularly how can I kill an app by its full name?

1
  • 1
    kill $(ps aux | awk '/app1\/main/ {print $2}')
    – c4f4t0r
    Jun 4, 2018 at 6:42

2 Answers 2

0

If you only need to support Linux (which I guess is the case given that your question is tagged linux), you can make use of the /proc/%d/exe symlinks.

Here is an example of what a script to do that could look like.

#!/bin/bash

if [ "$#" != 1 ] || [ "$1" = "" ]
then
    echo "Usage: $0 <full-exe-path>" 1>&2
    exit 1
fi

shopt -s extglob
cd /proc

for PID in [1-9]*([0-9])
do
    if [ "$(readlink "$PID"/exe)" = "$1" ]
    then
        kill "$PID"
    fi
done

One caveat to notice is that if the process ID is a kernel thread or is not owned by you readlink will fail and "$(readlink "$PID"/exe)" will evaluate to an empty string. To avoid attempting to kill all of those processes the script will refuse to do anything if $1 is an empty string.

Also notice that this script makes use of extglob which allows matching directories with [1-9]*([0-9]) which means a character in the interval 1-9 followed by any number of characters in the interval 0-9.

0

I do this in a one-liner with piping (you need gawk and xargs):

$>ps -ax | grep "/app2/main" | grep -v "grep" | gawk '{print $1}' | xargs kill

what is happening here?

ps -ax  # — list all processes in extended format
grep "/app2/main"  # — show only processes that contain "/app2/main"
grep -v "grep"  # — sort out the previous grep process with the mentioned string
gawk '{print $1}'  # — use gawk to pick only the first column (process id)
xargs kill  # — use xargs to pass pid to kill as an argument

This effectively sends a kill signal to the process you need. You may wrap it in a bash script, if you want a short command with an argument.

You must log in to answer this question.