0

Running ./run_func_and_get_pid.sh that has the following contents

#!/bin/bash

run () {
    while true
    do
        "$@" & echo -n $! > duh && echo "" `cat duh` `cat dih`
        sleep 5
    done
}

run echo -n my name is mudd & echo -n $$ > dih

outputs

my name is mudd 392056 392054
my name is mudd 392060 392054
my name is mudd 392066 392054
my name is mudd 392070 392054
my name is mudd 392074 392054
my name is mudd 392082 392054
my name is mudd 392087 392054
my name is mudd 392091 392054
my name is mudd 392095 392054
my name is mudd 392122 392054
my name is mudd 392126 392054
my name is mudd 392130 392054
my name is mudd 392134 392054
my name is mudd 392139 392054
my name is mudd 392143 392054
my name is mudd 392147 392054
my name is mudd 392151 392054
my name is mudd 392160 392054
my name is mudd 392164 392054
. . .

This post suggests that 392054 would be the pid of run_func_and_get_pid.sh but then I see

$ ps aux | grep run_func
. . .
user   392055  0.0  0.0   9632  1852 pts/5    S    09:51   0:00 /bin/bash ./run_func_and_get_pid.sh
user   398763  0.0  0.0   9040  2508 pts/6    S+   10:10   0:00 grep -I --color=auto run_func

$ ps aux | grep 392054
user   398975  0.0  0.0   9040   720 pts/6    S+   10:13   0:00 grep -I --color=auto 392054

I can only guess that 392054 is the bash shell spawned when I ran the command. Whatever the process was, it has already exited.

How do I get the PID of the script I'm running instead of the parent of the script?

2 Answers 2

1

this:

run ... & echo ...

forks a new shell process to run run in the background, and then continues the main script with the echo. The latter won't run for long, so the main script exits rather quickly, and indeed $$ then points to an already exited process.

In the version in your answer, you're not starting a background process for run (and indeed there doesn't seem to be a reason for that), so it runs in the same process as the main script.

For a perhaps simpler example, try e.g.

#!/bin/bash
echo "main script: $$"
f() {
    sleep 5;
    echo "bg job: $BASH_PID"
    ps "$BASH_PID";
}
f &

and so:

$ bash bg.sh; sleep 3
main script: 32553
bg job: 32554
  PID TTY      STAT   TIME COMMAND
32554 pts/1    S      0:00 bash bg.sh
0

I did not have an answer to this question when I started but have now discovered the answer.

392054 appears to be the PID of the run function because if I modify the script to do the following, I get what I was expecting:

#!/bin/bash

run () {
    while true
    do
        "$@" & echo -n $! > duh && echo "" `cat duh` `cat dih`
        sleep 5
    done
}

echo -n $$ > dih
run echo -n my name is mudd

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .