0

I have a script which performs various operations on a list of hosts. However one of the loops only applies the operation to the first entry in the file, and I can't see why.

    # this loop shows multiple entries in the file...
    while read -r target_host ; do
        echo "%% read $target_host"
    done <"${PHASE_TWO_FILE}"
# this loop only goes around once then exits....
while read -r target_host ; do
    cmd=&quot;ssh user@cmk.southwold.net 'applyrrdupg.sh ${target_host}'&quot;
    echo &quot;DEBUG: Running $cmd&quot;
    $cmd &gt;&gt;&quot;$ERRORS_FILE&quot;
    RC=$?
    if [ 0 -eq &quot;$RC&quot; ]; then
        echo &quot;SUCCESS: convert ${target_host}&quot;
        echo &quot;$target_host&quot; &gt;&gt;&quot;${PHASE_THREE_FILE}&quot;
        echo -e &quot;HOST: $target_host\nSUCCESS\n--&quot; &gt;&gt;&quot;$ERRORS_FILE&quot;
    else
        echo &quot;ERROR: rrd conversion failed for $target_host&quot;
        REVIEW_ERRORS=1
        echo -e &quot;HOST: $target_host\nERROR: Conversion failed\nDETAILS: see above\n--&quot; &gt;&gt;&quot;$ERRORS_FILE&quot;
    fi
done &lt;&quot;${PHASE_TWO_FILE}&quot;
echo &quot;%% loop exited&quot;

# and just to make sure - lets check again....
while read -r target_host ; do
    echo &quot;%% read $target_host&quot;
done &lt;&quot;${PHASE_TWO_FILE}&quot;

This produces the output:

%% read centos5.southwold.net
%% read centos7.southwold.net
%% read cmk-satellite.southwold.net
DEBUG: Running ssh user@cmk.southwold.net 'applyrrdupg.sh centos5.southwold.net'
SUCCESS: convert centos5.southwold.net
%% loop exited
%% read centos5.southwold.net
%% read centos7.southwold.net
%% read cmk-satellite.southwold.net

What am I missing?

symcbean
  • 5,540
  • 1
    Does applyrrdupg.sh read from stdin? – Chris Davies Jan 29 '24 at 12:41
  • Well spotted. It shouldn't, however when I changed $cmd >>"$ERRORS_FILE" to echo "" | $cmd >>"$ERRORS_FILE" the loop iterates as epxected and my sanity is restored. If you copy and paste your comment as an answer, I'll tick the box. – symcbean Jan 29 '24 at 12:47
  • I was writing an answer addressing this and other issues with the code, but it's been closed. (For example, while …; do IFS= read -r …, ssh -qn …, and importantly don't use scalar variables to hold code.) – Chris Davies Jan 29 '24 at 12:49

0 Answers0