Continuing the drama of little snippets of shell

This little piece of shell script attempts to find the ‘lowest subprocess’ of a passed in process. It works well with a straight tree of processes, and if there are the occasional pipes in the command tree then it will miss them most of the time.
Maybe tomorrow I’ll talk about how to fix it.

function find_lowest_subprocess() {
local -i parent=$1
local pids
typeset -a pids
pids=$(pgrep -P $parent)
while [[ -n "$pids" ]]; do
if (( ${#pids[@]} > 1 )); then
local i=0
while (( i < ${#pids[@]} )); do
local sub=$(pgrep -P ${pids[$i]})
[[ -n $sub ]] && parent=$sub
((i=i + 1))
done
else
parent=$pids
fi
pids=$(pgrep -P $parent)
done
echo $parent
}