0

Right now, my bash script works for 1 PID processes and I must use an exact process name for input. It will not accept *firefox*' for example. Also, I run a bash script that opens multiplersync` processes, and I would like this script to kill all of those processes. But, this script only works on processes with 1 PID.

Here is the script:

#!/bin/bash

    createProcfile() {

    ps -eLf | grep -f process.tmp | grep -v 'grep' | awk '{print $2,$10}' | sort -u | egrep -o '[0-9]{4,}' > pid.tmp

#   pgrep "$(cat process.tmp)" > pid.tmp

    }

    PIDFile=pid.tmp

    echo "Enter a process name"
    read -r process
    echo "$process" > process.tmp

#   node_process_id=$(pidof "$process")
    node_process_id=$(ps -eLf | grep $process | grep -v 'grep' | awk '{print $2,$10}' | sort -u | egrep -o '[0-9]{4,}')
    if [[ -z "$node_process_id" ]]; then
            echo "Please enter a valid process."
        rm process.tmp
        exit 0
    fi

    ps -eLf | grep $process | awk '{print $2,$10}' | sort -u | grep -v 'grep'
#   pgrep "$(cat process.tmp)"

    echo "Would you like to kill this process(es)? (y/n)"
    read -r answer

    if [[ "$answer" == y ]]; then

        createProcfile
        pkill -F "$PIDFile"
        rm "$PIDFile"
        sleep 1
        createProcfile

        node_process_id=$(pidof "$process")
        if [[ -z $node_process_id ]]; then
                echo "Process terminated successfully."
            rm process.tmp
            exit 0
        else
            echo "Process not terminated. Kill process manually."
            ps -eLf | grep $process | awk '{print $2,$10}' | sort -u | grep -v 'grep'
#           pgrep "$(cat process.tmp)"
            rm "$PIDFile"
            rm process.tmp
            exit 0
        fi
    fi

I edited the script. Thanks to your comments, it works now and does the following:

  1. Make script accept partial name as input
  2. Kill more than 1 PID

Thank you!

Debug255
  • 335
  • 3
  • 17

2 Answers2

0
 It will not accept *firefox*

Use killall command. Example :

killall -r "process.*"

This will kill all the processes whose names contain process in the beginning followed by any stuff.

The [ manual ] says :

-r, --regexp
Interpret process name pattern as an extended regular expression.

Sidenote:

Note that we have to double quote the regular expression to prevent file globbing.
(Thanks @broslow for reminding this stuff).

Community
  • 1
  • 1
sjsam
  • 21,411
  • 5
  • 55
  • 102
0

pkill exists to solve your problem. It accepts a pattern to match against the process name, or the entire command line if -f is specified.

iruvar
  • 22,736
  • 7
  • 53
  • 82
  • The part of the script that I need to accept a partial name should not also kill the process. So, I can't use that. I edited my script to show you what I did to fix it or to use as a 'work-around' – Debug255 Jun 03 '16 at 01:28