Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

while read line stops after first iteration [duplicate]

I am trying to execute a simple script to capture multiple server's details using svmatch on server names input from a file.

#!/bin/sh
while read line; do
svmatch $line
done < ~/svr_input;

The svmatch command works with no problem when executed as a stand along command.

like image 678
Manish Singh Avatar asked Dec 25 '22 13:12

Manish Singh


1 Answers

Redirect your inner command's stdin from /dev/null:

svmatch $line </dev/null

Otherwise, svmatch is able to consume stdin (which, of course, is the list of remaining lines).

The other approach is to use a file descriptor other than the default of stdin:

#!/bin/sh
while IFS= read -r line <&3; do
  svmatch "$line"
done 3<svr_input

...if using bash rather than /bin/sh, you have some other options as well; for instance, bash 4.1 or newer can allocate a free file descriptor, rather than requiring a specific FD number to be hardcoded:

#!/bin/bash
while IFS= read -r -u "$fd_num" line; do
  do-something-with "$line"
done {fd_num}<svr_input
like image 191
Charles Duffy Avatar answered Jan 15 '23 08:01

Charles Duffy