I am wondering how to wait for any process to finish in macOS, since `wait -n` doesn't work. I have a script doing several things, and in some point it will enter a loop calling another script to the background to exploit some parallelism, but not more than X times since it wouldn't be efficient. Thus, I need to wait for any child process to finish before creating new processes.

I have seen [this question](https://stackoverflow.com/questions/68752256/how-can-i-wait-any-child-process-exit-on-macos) but it doesn't answer the "any" part, it just says how to wait to a specific process to finish.

I've thought of either storing all PIDs and actively checking if they're still running with `ps`, but it's very slapdash and resource consuming. I also thought about upgrading bash to a newer version (if that's ever possible in macOS without breaking how bash already works), but I would be very disappointed if there was no other way to actually wait for *any* process to finish, it's such a basic feature... Any ideas?

A basic version of my code would look like this:

```
for vid_file in $VID_FILES
do
    my_script.sh $vid_file other_args &
    ((TOTAL_PROCESSES=TOTAL_PROCESSES+1))
    if [ $TOTAL_PROCESSES -ge $MAX_PROCESS ]; then
        wait -n
        ((TOTAL_PROCESSES=TOTAL_PROCESSES-1))
    fi
done

```

My neither elegant nor performant approach to substitute the `wait -n`:

```
NUM_PROCC=$MAX_PROCESS
while [ $NUM_PROCC -ge $MAX_PROCESS ]
do
    sleep 5
    NUM_PROCC=$(ps | grep "my_script.sh"| wc -l | tr -d " \t")
    # grep command will count as one so we need to remove it
    ((NUM_PROCC=NUM_PROCC-1))
done

```

PS: This question could be closed and merged with the one I mentioned above. I've just created this new one because stackoverflow wouldn't let me comment or ask...

PS2: I do understand that my objective could be achieved by other means. If you don't have an answer for the specific question itself but rather a workaround, please let other people answer the question about "waiting any" since it would be very useful for me/everyone in the future as well. I will of course welcome and be thankful for the workaround too!

Thank you in advance!