#!/usr/bin/env bash

shopt -s lastpipe
set -x

: "${BASH_VERSION}"

wait_explicit_pids="${1:-true}"

declare -a pid=()
: <( sleep 8; ) ${ pid+=( ${!} ); } \
    <( sleep 6; ) ${ pid+=( ${!} ); } \
    <( sleep 4; ) ${ pid+=( ${!} ); } \
    <( sleep 2; ) ${ pid+=( ${!} ); }
SECONDS=0
: "${pid[*]@A}" \$\!=${!}
if [[ ${wait_explicit_pids} == 'true' ]]; then
  wait -- "${pid[@]}"
else
  wait
fi
: termination status ${?} at ${SECONDS} seconds

pid=()
printf 'The quick brown fox jumps over the lazy dog.\n' |
  tee -- >(
        set +x
        IFS='' read -r line
        sleep 8
        printf 'line length : %s\n' "${#line}" 
      ) ${ pid+=( ${!} ); } \
      >(
        set +x
        IFS='' read -r line
        sleep 6
        printf 'tortoise, actually : %s\n' "${line//dog/tortoise}" 
      ) ${ pid+=( ${!} ); } \
      >(
        set +x
        IFS='' read -r line
        sleep 4
        printf 'shouting : %s\n' "${line^^}" 
      ) ${ pid+=( ${!} ); } \
      >(
        set +x
        read -r -a line
        sleep 2
        line=( "${line[@]^}" )
        line=( "${line[@]/%[^.]/&.}" )
        printf 'overly emphatic : %s\n' "${line[*]}" 
      ) ${ pid+=( ${!} ); }
#
SECONDS=0
: "${pid[*]@A}" \$\!=${!}
if [[ ${wait_explicit_pids} == 'true' ]]; then
  wait -- "${pid[@]}"
else
  wait
fi
: termination status ${?} at ${SECONDS} seconds

: This breaks, but that is fine.
pid=()
declare -a fd=()
{ :; } {fd[0]}< <( sleep 4; ) ${ pid+=( ${!} ); } \
    {fd[1]}< <( sleep 6; ) ${ pid+=( ${!} ); } \
    {fd[2]}< <( sleep 8; ) ${ pid+=( ${!} ); } \
    {fd[3]}< <( sleep 10; ) ${ pid+=( ${!} ); }
SECONDS=0
: "${pid[*]@A}"
wait -- "${pid[@]}"
: termination status ${?} at ${SECONDS} seconds
