Bash EXIT trap with command substitution <p>I want a bash function to start a background process and set a trap to kill it when exiting. Something like:</p> <pre><code>function start { &lt;&lt;&lt;run process&gt;&gt;&gt; &amp; local pid="$!" trap "kill -9 $pid" EXIT echo $pid } </code></pre> <p>Now, if I just call this function directly, it works, but if I use command substitution to store pid for later use:</p> <pre><code>local pid=$(start) </code></pre> <p>Then apparently this starts another bash process and the trap is executed in it right after the function returns.</p> <p>Any way to make this work?</p>