How to get PID from forked child process in shell script

The PID of a backgrounded child process is stored in $!, and the current process is $$:

fpfunction &
child_pid=$!     # in parent process, child's pid is $!
parent_pid=$$    # in parent process, parent's pid is $$

When in the backgrounded function, the child processes’s PID is $BASHPID rather than $$, which is now the parent’s PID:

fpfunction() {
    local child_pid=$BASHPID   # in child process, child's pid is $BASHPID
    local parent_pid=$$        # in child process, parent's pid is $$
    ...
}

Also for what it’s worth, you can combine the looping statements into a single C-like for loop:

for ((n = 1; n < 20; ++n)); do
    echo "Hello World-- $n times"
    sleep 2
    echo "Hello World2-- $n times"
done

Leave a Comment