Home > OS >  how to copy a penultimate file from a SSH to local using a script
how to copy a penultimate file from a SSH to local using a script

Time:11-22

I'm new in bash scripting and I'm trying to make a script which can copy a penultimate file from a folder, from machine B (ssh) to machine A (local). For now I'm stuck at this point (see below) when I'm receiving an error when the script trying to copy the file.

Thank you in advance!

Input:

#!/bin/bash

userName=`whoami`
myLocation=`pwd`  #machineA or local

ssh $userName@machineB << 'ENDSSH'
pathFile="/somefolder/folder_1/businessfolder/"
cd $pathFile
ls -ltrh
zipFile=`ls -Art | tail -n 2 | head -1`
echo $zipFile
ENDSSH
scp $userName@machineB:$pathFile$zipFile $myLocation

Output (just error):

scp: .: not a regular file

CodePudding user response:

If you can touch ~/.hushlogin on machineB for userName the following should work (worked for me):

#!/bin/bash
userName=$(whoami)
myLocation=$(pwd)
pathFile="/somefolder/folder_1/businessfolder/"

zipFile=$(ssh -T -q $userName@machineB <<ENDSSH
cd $pathFile
ls -Art | tail -n 2 | head -1
ENDSSH
)
scp "$userName"@machineB:"$pathFile$zipFile" "$myLocation" 
  • Related