#!/usr/bin/env bash
sleep 3 & # Spawn a child
trap '
pgrep -P $$ # Outputs one PID as expected
PIDS=( $( pgrep -P $$ ) ) # Saves an extra nonexistant PID
echo "PIDS: ${PIDS[@]}" # You can see it is the last one
ps -o pid= "${PIDS[@]:(-1)}" ||
echo "Dafuq is ${PIDS[@]:(-1)}?" # Yep, it does not exist!
' 0 1 2 3 15
它输出
11800
PIDS: 11800 11802
Dafuq is 11802?
它只发生在陷阱中。为什么将不存在的 PID 附加到数组?以及如何避免这种奇怪的行为?