Search code examples
bashshellprocesspidsubshell

How can I store a subshell PID in a variable so that I can kill the subshell and its background process later?


So, let us say I am running a subshell with a background process as follows:

(command &)

I want to be able to store the PID of this subprocess into a bash variable so that I can kill the subshell and its running background process later. How can I do so?

Note: This may very well be a duplicate, but I am struggling to implement many of the other answers. So, even if this question is marked as a duplicate, I would appreciate it if someone could still provide an answer regardless.

Some things I have tried:

pid="$((echo "$BASHPID" && command &))"
pid2="$((command & echo "$BASHPID"))"
pid3=(echo "$BASHPID" && command &)
pid4=(command & echo "$BASHPID")

Solution

  • One idea:

    $ read -r x < <(sleep 240 & echo $!)       # alternative: replace $! with $BASHPID
                    ^^^^^^^^^        ^^    
    $ echo "$x"
    1887
    ^^^^
    $ ps -aef|egrep sleep
    myuser    1887       1 pty1     16:00:17 /usr/bin/sleep
              ^^^^                                    ^^^^^
    $ pgrep -a sleep
    1887 sleep 240
    ^^^^ ^^^^^^^^^