I have 3 Linux machines, namely client
, server1
and server2
.
I am trying to achieve something like this. I would like to copy the latest file in a particular directory of server1
to server2
. I will not be doing this by logging into server1
directly, but I always log on to client
machine first. Let me list down the step by step approach which is happening now:
- Log on to
client
machine using ssh - SSH into
server1
- Go to directory
/home/user1
inserver1
using the commandls /home/user1 -Art | tail -n 1
- SCP the latest file to
/home/user2
directory ofserver2
This manual operation is happening just fine. I have automated this using a one line script like below:
ssh user1@server1 scp -o StrictHostKeyChecking=no /home/user1/test.txt user2@server2:/home/user2
But as you can see, I am uploading the file /home/user1/test.txt
. How can I modify this script to always upload the latest file in the directory /home/user1
?
CodePudding user response:
If zsh
is available on server1, you could use its advanced globbing features to find the most recent file to copy:
ssh user1@server1 \
"zsh -c 'scp -o StrictHostKeyChecking=no /home/user1/*(om[1]) user2@server2:/home/user2'"
The quoting is important in case your remote shell on server1 is not zsh.
CodePudding user response:
You can use SSH to list the last file and after user scp to copy the file as follow:
FILE=$(ssh user1@server1 "ls -tp $REMOTE_DIR |grep -v / | grep -m1 \"\""); scp user1@server1:$FILE user2@server2:/home/user2
Before launch these command you need to set the remote directory where to search for the last modified file as:
REMOTE_DIR=/home/user1