How to save multiple $! into variables and use it later in bash?

前端 未结 3 1405
無奈伤痛
無奈伤痛 2021-01-27 07:02

I want to get the pids of two background processes,

sleep 20 & pid1=$\\!; sleep 10 & pid2=$\\!; echo \"pid1: $pid1, pid2: $pid2\"

and

相关标签:
3条回答
  • 2021-01-27 07:33

    The backslash is causing the value to be the string $! verbatim. Don't put a backslash in the assignment.

    On the command line, you may want to temporarily set +H to avoid getting event not found warnings; but this only affects the interactive shell. In a script, set -H is never active (and would be meaningless anyway).

    (I'm speculating this is the reason you put the backslash there in the first place. If not, simply just take it out.)

    0 讨论(0)
  • 2021-01-27 07:41

    I have accomplished this in the past by using bash arrays to hold the PIDs. I had a sequence of database imports to run and when handled sequentially they took ~8 hours to complete. I launched them all as background processes and tracked the list of PIDs to watch for completion and it got the processing time down to 45 minutes.

    Here is an example of launching background processes, storing the PIDs in an array, and then printing all of the array values:

    $ pids=()
    $ sleep 20 &
    22991
    $ pids+=($!)
    $ sleep 20 &
    23298
    $ pids+=($!)
    $ j=0;for i in "${pids[@]}";do ((j=j+1));echo 'pid'$j': '$i;done
    pid1: 22991
    pid2: 23298
    
    0 讨论(0)
  • 2021-01-27 07:47

    Your syntax kindly incorrect, try this:

    [root@XXX ~]# sleep 5 & pid1=$!; sleep 6 & pid2=$!; echo "pid1: ${pid1}, pid2: ${pid2}"
    [1] 2308
    [2] 2309
    pid1: 2308, pid2: 2309
    
    0 讨论(0)
提交回复
热议问题