laggardkernel

pitfall of while read

Jun 1st, 2019
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 0.73 KB | None | 0 0
  1. # A background process started within a loop may compete with
  2. # the loop for stdin, which causes the `while read` loop stop
  3. # after the 1st round.
  4.  
  5. cat << EOF >| tasklist.txt
  6. 1
  7. 2
  8. 3
  9. EOF
  10.  
  11. # Solution 1: remove stdin for background process.
  12. while read -r line; do
  13.   echo "$line"
  14.   # use htop as an example for background process
  15.   </dev/null htop &
  16.   # or
  17.   # htop </dev/null &
  18.   sleep 1
  19. done < tasklist.txt
  20.  
  21. # Solution 2: read lines into an array and do a `for` loop.
  22. # `mapfile/readarray` is available in Bash 4 to read lines
  23. # from file into an array.
  24. # -t indicates stripping the **trailing** newline.
  25. mapfile -t lines < tasklist.txt
  26. for line in "${lines[@]}"; do
  27.   echo "$line"
  28.   htop &
  29.   sleep 1
  30. done
  31. unset line
Advertisement
Add Comment
Please, Sign In to add comment