Why this script is not working as 'expected' when doing ssh with while read ... really confused?

Hi,

I have a script below that is running ssh <host> <command> on some servers.

Below is more or less the script. I have to modify it somehow to get rid of the 'confidential' hostnames

check_log.bash

#!/bin/bash
#

myPID=$$

parse_log ()
{
   sub="parse_log"
   host=${1}
   service=${2}

   echo
   echo "----------------------------------------------------------------"
   echo
   echo "... Parsing listener log on ${host}"

   cat /dev/null > ${sub}.${host}.tmp
   ssh ${host} find /u01/app/grid/diag/tnslsnr/${host} -name "listener*log" -print | tee -a ${sub}.${host}.tmp

   while read log
   do
      echo "     --> Searching ${log} for ${service} on ${host} ..."
      #ssh ${host} grep -i "${service}" ${log}
      #echo
   done < ${sub}.${host}.tmp

   echo
   echo "----------------------------------------------------------------"
   echo
}


########
# MAIN #
########

parse_log "host1" "test_app"
parse_log "host2" "test_app"
parse_log "host3" "test_app"

I am running the script on a mounted filesystem that is accessible to all hosts, i.e. for example /nfs/scripts. So the script is /nfs/scripts/check_log.bash and I just run it from host1 as ./check_log.bash.

So the first ssh below runs fine, it does the find and redirect the result to the .tmp file

   cat /dev/null > ${sub}.${host}.tmp
   ssh ${host} find /u01/app/grid/diag/tnslsnr/${host} -name "listener*log" -print | tee -a ${sub}.${host}.tmp

I then want to grep for a script like "test_app" from each file which is why I have the following while loop.

   while read log
   do
      echo "     --> Searching ${log} for ${service} on ${host} ..."
      #ssh ${host} grep -i "${service}" ${log}
      #echo
   done < ${sub}.${host}.tmp

So far so good, I tested and it does shows me the " Searching ..." string. However when I am now ready to run it the ssh and has uncommented the

#ssh ${host} grep -i "${service}" ${log}

. The while loop is not going thru all the file in the .tmp file, it is only doing it on the first file. It's as if after it run the first ssh it is breaking out of the while loop?

At first I thought maybe it has to do with using /bin/bash. Using /bin/ksh gives the same result.

Not sure what am doing wrong :slight_smile: Checking the .tmp file, I can see that each of them has about 6-7 files.

My first guess is that the while read opens the input and reads the first line, then ssh consumes all the residual lines from the input file. Try ssh -n .

But - the approach to loop through the input file and opening an ssh session for every single entry is resource hungry and far from optimal. How about creating a "search" file and running the grep from it in a single session?

Oops, just found the answer from Google. Using ssh -n gives me what I am wanting to do.

1 Like