morphynoman
morphynoman

Reputation: 23

Bash: read inside while loop

Let me introduce my loop to you all:

NUM_LINE=0
while read line; do
  let NUM_LINE+=1
  if [ $NUM_LINE -lt 41 ]; then
    echo -e "\t$BLANC|$ORIGINAL $line $BLANC|"
  else 
    echo -e "\n\t$BLANC## "$GRIS"Llista de Nodes sel·leccionats    $BLANC############$ORIGINAL\n"
    read AUX
    NUM_LINE=0  
  fi
done <$NODES

So that:


$BLANC is \033[1;37m
$GRIS same
$ORIGINAL as well
$NODES is the absolute path of a file containg a lot of lines like:
| 23127 myserver 98.194.263.29 |

The Problem:


The echo inside the else statement it's properly triggered. But it doesn't happen the same with the read statement

Any suggestion?

Upvotes: 2

Views: 2462

Answers (1)

jordanm
jordanm

Reputation: 34914

The reason that the loop doesn't function properly is because read is reading from stdin in both cases. You need to open an alternate file descriptor to your file and read from the file descriptor.

exec 3<$NODES
NUM_LINE=0
while read -u 3 -r line; do
  (( NUM_LINE++ ))
  if (( NUM_LINE < 41 )); then
    echo -e "\t$BLANC|$ORIGINAL $line $BLANC|"
  else 
    echo -e "\n\t$BLANC## "$GRIS"Llista de Nodes sel·leccionats    $BLANC############$ORIGINAL\n"
    read AUX
    NUM_LINE=0  
  fi
done

Upvotes: 5

Related Questions