2

Is there a way, I can find the process name of bash script by the shell script that was used to invoke it? or can I set process name of bash script to something such as

-myprocess

(I have looked into argv[0], but I am not clear about it)

so when I use

ps -ef | grep -c '[M]yprocess'

I get only all the instances of myprocess?

John1024
  • 109,961
  • 14
  • 137
  • 171
Vijay Shekhawat
  • 149
  • 2
  • 13
  • What do you mean by "process name"? Processes have process identifiers (PIDs), but they don't have names. Do you mean perhaps *program* name? Would `ps -p $PPID` help? If you are on Linux there is some `/proc/$PPID` magic you might be able to do. – cdarke Feb 19 '18 at 10:43
  • By process name, I mean that if I do not know the PID of a given process it can I somehow find the PID or Process Name in Unix by the parent script that starts that process? – Vijay Shekhawat Feb 19 '18 at 11:39
  • The program name will be `bash` (or whatever shell you are using) with a parameter of the script name. You can find the parent's pid using `$PPID`. Are you on Linux? – cdarke Feb 19 '18 at 15:31

3 Answers3

2

To obtain the command name of the current script that is running, use:

ps -q $$ -o comm=

To get process information on all running scripts that have the same name as the current script, use:

ps -C "$(ps -q $$ -o comm=)"

To find just the process IDs of all scripts currently being run that have the same name as the current script, use:

pgrep "$(ps -q $$ -o comm=)"

How it works

$$ is the process ID of the script that is being run.

The option -q $$ tells ps to report on only process ID $$.

The option -o comm= tells ps to omit headers and to skip the usual output and instead print just the command name.

John1024
  • 109,961
  • 14
  • 137
  • 171
0

The parent process id can be obtained from $PPID on bash and ksh. We can read the fields from ps into an array.

For bash you can try this. The problem with ps is that many options are non-standard, so I have kept that as generic as possible:

#!/bin/bash

while read -a fields
do
    if [[ ${fields[0]} == $PPID ]]
    then
        echo "Shell: ${fields[3]}"
        echo "Command: ${fields[4]}"
    fi
done < <(ps -p $PPID)

You have tagged bash and ksh, but they have different syntax rules. To read into an array bash uses -a but ksh uses -A, So for korn shell you would need to change the read line (and the #! line):

while read -A fields
cdarke
  • 42,728
  • 8
  • 80
  • 84
0

Not sure what you mean by that, but let's go with an example script b.sh.

#!/usr/local/bin/bash

echo "My name is $0, and I am running under $SHELL as the shell."

Running the script will give you:

$ bash b.sh
My name is b.sh, and I am running under /usr/local/bin/bash as the shell.

For more check this answer: HOWTO: Detect bash from shell script

Xsub
  • 1