0
t1=`cat final-md5sum | awk '{print $3}'`
t2=`cat final-md5sum | awk '{print $5}'`

for ip in $t1; do
        for  path in $t2; do
        echo "Node Name: " $ip "| Out-Of-Sync File Details: " $path `ssh root@$ip stat -c%y $path | cut -d'.' -f1`
        done
done

Contents of final-md5sum:

$ cat final-md5sum
Node Name: 192.168.1.2 Out-ofSync-Filename: /home/user1/file1
Node Name: 192.168.1.3 Out-ofSync-Filename: /home/user3/file4

My current Output:

Node Name:  192.168.1.2 | Out-Of-Sync File Details:  /home/user1/file1 2021-07-19 19:25:37
Node Name:  192.168.1.2 | Out-Of-Sync File Details:  /home/user1/file1 2021-07-19 19:25:37
Node Name:  192.168.1.3 | Out-Of-Sync File Details:  /home/user3/file4 2021-07-19 19:14:09
Node Name:  192.168.1.3 | Out-Of-Sync File Details:  /home/user3/file4 2021-07-19 19:14:09

Expected Output:

Node Name:  192.168.1.2 | Out-Of-Sync File Details:  /home/user1/file1 2021-07-19 19:25:37
Node Name:  192.168.1.3 | Out-Of-Sync File Details:  /home/user3/file4 2021-07-19 19:14:09

I'm getting duplicate values in my output. What am I doing wrong here?

3
  • Your approach will check for each file on each server. 2 files times 2 servers = 4 output lines. What I do not understand is why the filename is repeated, the second line should be 192.168.1.2 and file4 instead of file1.
    – Panki
    Jul 21, 2021 at 17:24
  • Yes. I want to modify my FOR loop to avoid this duplicate values. I tried all indentations for my nested FOR loop but still I'm getting duplicate values in my output.
    – n1Ls
    Jul 21, 2021 at 17:31
  • Why are you using nested loops in the first place? You can parse the file line by line, no dupes that way.
    – Panki
    Jul 21, 2021 at 17:33

1 Answer 1

1

You're getting duplicates because you're using nested loop, so the inner loop will run twice for each outer loop (since you have two lines). I don't quite see what else you were expecting. A simple solution is not to use two loops:

awk '{print $3, $5}' final-md5sum | 
    while read -r ip path; do 
        echo "Node Name: " $ip "| Out-Of-Sync File Details: " $path `ssh root@$ip stat -c%y $path | cut -d'.' -f1`
    done

Or, more legibly in my opinion:

awk '{print $3, $5}' final-md5sum | 
    while read -r ip path; do 
        sshOutput=$(ssh root@"$ip" stat -c%y "$path" | cut -d'.' -f1)
        echo "Node Name: $ip | Out-Of-Sync File Details: $path $sshOutput"
    done

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .