Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laggardkernel/e80b170b2f3d55983c42986f996f25c4 to your computer and use it in GitHub Desktop.
Save laggardkernel/e80b170b2f3d55983c42986f996f25c4 to your computer and use it in GitHub Desktop.
pitfall of while read #bash
# 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