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

68 views Asked by At

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")
3

There are 3 answers

1
markp-fuso On BEST ANSWER

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
^^^^ ^^^^^^^^^
0
KamilCuk On

There are many ways of https://en.wikipedia.org/wiki/Inter-process_communication . For example use a fifo:

pidfile=$(mktemp -n)
mkfifo "$pidfile"
(command & echo $! > "$pidfile")
read pid < "$pidfile"
rm "$pidfile"
0
Diego Torres Milano On

Perhaps the shortest way of achieving it is using coproc:

#! /bin/bash

coproc ./mycommand
pid=$COPROC_PID