Created
June 18, 2019 05:31
-
-
Save laggardkernel/e80b170b2f3d55983c42986f996f25c4 to your computer and use it in GitHub Desktop.
pitfall of while read #bash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# A background process started within a loop may compete with | |
# the loop for stdin, which causes the `while read` loop stop | |
# after the 1st round. | |
cat << EOF >| tasklist.txt | |
1 | |
2 | |
3 | |
EOF | |
# Solution 1: remove stdin for background process. | |
while read -r line; do | |
echo "$line" | |
# use htop as an example for background process | |
</dev/null htop & | |
# or | |
# htop </dev/null & | |
sleep 1 | |
done < tasklist.txt | |
# Solution 2: read lines into an array and do a `for` loop. | |
# `mapfile/readarray` is available in Bash 4 to read lines | |
# from file into an array. | |
# -t indicates stripping the **trailing** newline. | |
mapfile -t lines < tasklist.txt | |
for line in "${lines[@]}"; do | |
echo "$line" | |
htop & | |
sleep 1 | |
done | |
unset line |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment