Shell – bash – get pid for a script using the script filename

processscriptingshell-script

I have two scripts:

  • running_script
  • script_one

I need to get the PID for the/any instances of running_script running under a username, and then pkill to stop the running_script and daughter processes.

We expected something like:

ps -fu will | grep running_script

to find the running_script process(es). However checking the PID against the ps command output show that the cmd as: "bin/bash" for the running_script process.

running_script runs as a detached process(& operator) which starts script_one. I print the PID-s at the start to compare with ps command's output.

running_script  &
echo $! -- $BASHPID

In the real use-case, we won't have PIDs for some running_script processes running. Also, script_one may or may not be a detached process from the running_script parent.

For the purposes of the exercise, script_one just does loops.

while [ true ]
do
    echo "  $0 - 35sec ..."
    sleep 35
done

However that's just the example. The requirement is to get PID for the parent, running_script process(es).

Is there an option on ps or another command that can give me the name of the script file and the PID? Or a method to set a name that can be searched for?

In the final use-case, there could be several instances of running_script so picking them out by name seems the best option to date.

example

I thought it might help to show what the ps command shows, since most responses appear to think that's going to work. I ran this example just a while ago.

$  ./running_script &
$  echo $! - $BASHPID
9047 - 3261
$  ps -ef | grep will

  UID     PID  PPID  C STIME TTY          TIME CMD
  will   8862  2823  0 22:48 ?        00:00:01 gnome-terminal
  will   8868  8862  0 22:48 ?        00:00:00 gnome-pty-helper
  will   8869  8862  0 22:48 pts/4    00:00:00 bash
* will   9047  3261  0 22:55 pts/2    00:00:00 /bin/bash
  will   9049  9047  0 22:55 pts/2    00:00:00 /bin/bash
  will   9059  2886  0 22:56 pts/0    00:00:00 man pgrep
  will   9070  9059  0 22:56 pts/0    00:00:00 pager -s
  will  10228  9049  0 23:31 pts/2    00:00:00 sleep 35
  will  10232  8869  0 23:31 pts/4    00:00:00 ps -ef
  will  10233  8869  0 23:31 pts/4    00:00:00 grep --colour=auto william

I have marked PID #9047, is simply shows:
– will 9047 3261 0 22:55 pts/2 00:00:00 /bin/bash

Is there something like a a "jobname" attribute I could set on linux?

Best Answer

Try pgrep -f running_script -- the -f option uses the whole command line to match against, not just the process name

Related Question