How to get the pid of the last executed command in shell script?

I intend to have a shell manuscript similar to this:

my-app &
echo $my-app-pid

But I do not recognize just how the get the pid of the simply implemented command.

I recognize I can simply make use of the jobs -p my-app command to grep the pid. Yet if I intend to execute the shell numerous times, this method will certainly not function. Due to the fact that the jobspec is unclear.

324
2022-06-06 12:31:20
Source Share
Answers: 2

Try something similar to this:

 ps ef | grep "[m]y-app" | awk '{print $2}'

Placing the first letter of your process in between [ ] sees to it you do not get the grep process in your checklist. If required you can additionally add a grep on your username.

3
2022-06-06 12:52:15
Source

The PID of the last implemented command remains in the $! shell variable:

my-app &
echo $!
425
2022-06-06 12:51:44
Source