bash shell process – How to Get the PID of the Last Executed Command in Shell Script?

background-processbashprocessshell

I want to have a shell script like this:

my-app &
echo $my-app-pid

But I do not know how the get the pid of the just executed command.

I know I can just use the jobs -p my-app command to grep the pid. But if I want to execute the shell multiple times, this method will not work. Because the jobspec is ambiguous.

Best Answer

The PID of the last executed command is in the $! shell variable:

my-app &
echo $!
Related Question