shell

getting pid of the background job using "$!"


I've a written a shell script to launch multiple background jobs and store the process id's of them in an array using $!. In the end I print all the process id's by iterating through the array. I want to know is the shell script written has a bug? And, the reason I feel there is a bug in my shell script is because $! might return the process id of another process if in case there are multiple processes being created in my PC.

#!/bin/bash

ps -a & pids+=($!) #Does $! return process id of command ps -a for sure
ls -la & pids+=($!) #Does $! return process id of command ls -la for sure
echo ${pids[0]}
echo ${pids[1]}

Solution

  • $! "expands to the process ID of the most recently executed background (asynchronous) command" (source: bash manual)

    The variable is local to the current shell instance, so anything that happens outside of the current shell script/session is not relevant.

    If you place two processes in the background:

    ps -a &
    ls -la &
    

    Then $! will contain the PID of the last backgrounded process (in this case, ls -la).