#!/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
It outputs
11800
PIDS: 11800 11802
Dafuq is 11802?
It only happens with traps. Why is a nonexistent PID appended to the array? And how to avoid this odd behaviour?