'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 -eterminates 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 iis initialized with0or uninitialized, and uninitialized variables are equal to0in arithmetic contexti%Nis 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 |
