2

I was able to do it with one server with the following code:

ssh server001 << EOF
cat /dir/file001.txt >> somefile
EOF

With multiple servers, my script is able to ssh into the servers but for some reasons, it cannot find my file00x files and gives me the following error: cat: /dir/file00x.txt: No such file or directory even though the file does exist.

Here is my code:

 for i in {10..15}; do
    ssh $i      //for simplicity, theres some text manipulation to get the actual name of the server
    cat /tmp/$i.txt
 done << newfile.txt

I have also tried this method (clearly not the right way), but the file is still not found:

 for i in {10..15}; do
    ssh $i      
    cat /tmp/$i.txt >> newfile.txt
 done 

Tried this too but doesn't work either:

 for i in {10..15}; do
    ssh $i  << EOF    
    cat /tmp/$i.txt >> newfile.txt
    EOF
 done 
  • Is the /tmp/$i.txt file on the local machine or the remote machine? Is newfile.txt on the local machine or the remote machine? – Stephen Harris Aug 21 '16 at 18:59
  • /tmp/$i.txt is on the remote machine but newfile.txt is on a shared file system that can be accessed by both remote and local machines – user3669481 Aug 21 '16 at 19:26
0

So as I understand the question, you need to access /tmp/$i.txt on the remote machine, and it doesn't matter where newfile.txt is accessed from.

In this case we don't need to worry about HERE documents or being clever, a simple

ssh $i cat /tmp/$i.txt >> newfile.txt

will run the cat on the remote machine, but will append locally.

This can then be looped:

for i in {10..15}
do
  ssh $i cat /tmp/$i.txt >> newfile.txt
done

If, instead, you wanted the redirection to also occur on the remote machine then we can quote the command:

for i in {10..15}
do
  ssh $i "cat /tmp/$i.txt >> newfile.txt"
done

Now the cat $i.txt >> newfile.txt happens on the remote machine.

In your setup it shouldn't matter.

  • Looks like I need to ssh and cat in the same line..weird.. – user3669481 Aug 22 '16 at 11:07
  • 1
    ssh host cmd means "connect to host and run cmd". If you had it on two lines then it means "create interactive session on host and when that finishes run cmd locally"; something totally different :-) – Stephen Harris Aug 22 '16 at 11:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.