Karan Kohli Karan Kohli - 5 months ago 15
Linux Question

Scripting: reading file from remote machine and store in dir variable

I have two machines.. Im running a bash shell from remote machine where i do a ssh to the machines (ssh keys already shared) and then try reading from a file.
However, when I do a ssh it goes into prompt.. wait for some command and then executes the next line of the script.

Proc_m1_s1$ cat CleanCounters.txt
/root/karan/Logs/Counters/
/root/karan/Logs/Signalling/


Script

while [ $i -le 12 ]
do
IP_Addr="IP$i"
ssh $UNAME@${!IP_Addr}
for dir in $(cat /root/karan/bin/CleanCounters.txt); do
find $dir -name "A*" -type f -mtime +60 |xargs rm -f
done
i=$(( i+1 ))
done


I get the result in the following way...

[csbackup@muarchive BackupFolderNames]$ /home/csbackup/BackupFolderNames/CleanLogs_MUTUNDWE.sh
Last login: Tue Jun 23 11:13:14 2015 from o2net2
Proc_m1_s1$
Proc_m1_s1$ exit
logout
Connection to 10.0.0.1 closed.
cat: /root/karan/bin/CleanCounters.txt: No such file or directory*


Can anyone help me out so that i can remotely cat the lines of the file in dir variable and use it my script

Answer

Execute remote commands via ssh as follows (example cats /etc/hosts and stores it in a local variable):

result=`ssh $UNAME@${!IP_Addr} "cat /etc/hosts"`

This would answer the question stated in the title. For your for loop application, you would either have to write the entire command in one line or send a multi-line string as ssh parameter. Of course, you do things multiple times, which lead to multiple outputs. This output would then be stored in a single variable. In order to split this later on and assign this to the different loop values, add a "separator string" to the output, which you can then use to split the string later on.