TransWikia.com

FTP file transfer, loop through a directory and copy old files

Server Fault Asked by Mich Dart on February 4, 2021

I would like to move files older than 30 days and copy them into a remote FTP server.

I’ve already written this script, that is able to connect via FTP.

Usually, to move files, I would run this line:

find ./logs/ -type f -mtime +30 -exec mv {} destination ;

The problem is FTP doesn’t recognize that command. So I think I should loop through files and move only those that are older than 30 days. But I’m not an expert in bash.

Can anyone help me please?

#!/bin/bash

HOST=xxx             #This is the FTP servers host or IP address.
USER=xxx                     #This is the FTP user that has access to the server.
PASS=xxx              #This is the password for the FTP user.

# Call 1. Uses the ftp command with the -inv switches. 
#-i turns off interactive prompting. 
#-n Restrains FTP from attempting the auto-login feature. 
#-v enables verbose and progress. 

ftp -inv $HOST << EOF

# Call 2. Here the login credentials are supplied by calling the variables.

user $USER $PASS

pass

# Call 3. I change to the directory where I want to put or get
cd /

# Call4.  Here I will tell FTP to put or get the file.
find ./logs/ -type f -mtime +30 -exec echo {} ;
#put files older than 30 days

# End FTP Connection
bye

EOF

One Answer

You cannot use shell commands (like find) in an ftp script.

Though you can use a shell script to generate the ftp script.

echo open $HOST > ftp.txt
echo user $USER $PASS >> ftp.txt
find ./logs/ -type f -mtime +30 -printf "put logs/%f %fn" >> ftp.txt
echo bye >> ftp.txt

ftp < ftp.txt

The above code will generate file ftp.txt with commands and pass that to ftp. The generated ftp.txt will look like:

open host
user user pass
put logs/first.log first.log
put logs/second.log second.log
put logs/third.log third.log
...
bye

Answered by Martin Prikryl on February 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP