'wait swallows echo from background process

I am trying to use the "Parallel runs in N-process batches" approach from https://unix.stackexchange.com/a/216475/259719 and I am struggling to get it to work. Because my task involves an echo to stdout, which somehow get swallowed in this solution.

Does not work:

#!/bin/bash
set -e

N=8
for num in $(seq 10); do
    ((i=i%N)); ((i++==0)) && wait
    (
        echo "${num}"
    )&
done

Does work:

#!/bin/bash
set -e

N=8
for num in $(seq 10); do
    wait
    (
        echo "${num}"
    )&
done

Also works

#!/bin/bash
set -e

N=8
for num in $(seq 10); do
    (
        echo "${num}"
    )&
done
wait

I am really struggling to understand why nothing is echoed out in the first example.



Solution 1:[1]

set -e
((i=i%N))

Facts:

  • set -e terminates the program if any command exits with nonzero exit status (except exceptions).
  • (( exits with nonzero exit status if the expression inside is equal to zero
  • assignment = in arithmetic context is equal to the assigned value
  • i is initialized with 0 or uninitialized, and uninitialized variables are equal to 0 in arithmetic context
  • i%N is equal to 0

why nothing is echoed out

The script terminates because i%N == 0, so echo is never executed.


if (( i++ % N == 0 )); then
    wait
fi

or

if (( i %= N , i++ == 0 )); then

or

(( i %= N )) || :
# or (( i %= N , 1 ))
if (( i++ == 0 )); then

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1