在嵌套 for 循环中获取重复输出

在嵌套 for 循环中获取重复输出
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

内容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

我当前的输出:

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

预期输出:

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

我的输出中出现重复值。我在这里做错了什么?

答案1

您会得到重复项,因为您使用的是嵌套循环,因此内部循环将为每个外部循环运行两次(因为您有两行)。我不太明白你还期待什么。一个简单的解决方案是不使用两个循环:

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

或者,我认为更清晰的是:

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

相关内容