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?