Format output of the bash script to perform ssh operations on it further

bashshell-scriptssh

I have a file where my script outputs IP and file paths. I want to process that file further where it could automatically ssh to that IP and take file stat of that path from respective IP

cat final-list
Node Name: 192.168.1.6 Out-ofSync-Filename: /home/user/nginx/Templates/file1
Node Name: 192.168.1.7 Out-ofSync-Filename: /home/user/nginx/createfile /home/user/nginx/Templates/file3
Node Name: 192.168.1.8 Out-ofSync-Filename: /home/user/nginx/nginx/Templates/file1 /home/user/nginx/nginx/Templates/file5 /home/user/nginx/nginx/Templates/file3 /home/user/nginx/nginx/Templates/file9 /home/user/nginx/nginx/file12 /home/user/nginx/Templates/file56

My script for parsing above file:

xargs -n1 < final-list | grep -v "Name:" | grep -v "Node" | grep -v "Out-ofSync-Filename:"

192.168.1.6
/home/user/nginx/Templates/file1
192.168.1.7
/home/user/nginx/createfile
/home/user/nginx/Templates/file3
192.168.1.8
/home/user/nginx/nginx/Templates/file1
/home/user/nginx/nginx/Templates/file5
/home/user/nginx/nginx/Templates/file3
/home/user/nginx/nginx/Templates/file9
/home/user/nginx/nginx/file12
/home/user/nginx/Templates/file56

It has IP and respective files(filepaths per IP may increase in future) for which I want to find out last modified time of that file by ssh into that server IP using respective Path.

Best Answer

Reading from your final-list directly and assuming that the remote system is a Linux system:

while read -r a1 a2 remote a3 pathnames
do
    ssh -n "$remote" stat -c %n:%y "$pathnames"
done <final-list

This further relies on the pathnames in the list of pathnames to be nice, i.e. that they contain no embedded whitespace characters or filename globbing characters. It loops through the lines of final-list and calls stat on the remote system with the list of pathnames as argument.

The a1, a2, and a3 variables read with read are dummy variables whose values we aren't interested in. a1 will have the value Node, a2 will have the value Name:, and a3 will have the value Out-ofSync-Filename:.

The -n option to ssh is needed to stop ssh from reading the data stream that the loop is reading from.

The stat call uses the output format %n:%y which will produce a list of pathname:human-readable-modification-time lines. Use %Y in place of %y to get a Unix timestamp instead.

Related Question