我终于让这个脚本正常工作了,它登录到我的远程FTP并删除文件夹中超过N天的文件。然而,我无法让它也删除递归目录。可以更改或添加哪些内容以使此脚本删除子文件夹中的文件以及早于N天的子文件夹?我试过在一些地方添加-r函数,但没有成功。我认为它需要添加到脚本构建要删除的文件列表的位置。如有任何帮助,我们将不胜感激。提前谢谢!
#!/bin/bash
# Simple script to delete files older than specific number of days from FTP.
# This script use 'lftp'. And 'date' with '-d' option which is not POSIX compatible.
# FTP credentials and path
FTP_HOST="xxxxxxxxxxxx"
FTP_USER="xxxxxx"
FTP_PASS="xxxxxxxxxxxxxxxxx"
FTP_PATH="/directadmin"
# Full path to lftp executable
LFTP=`which lftp`
# Enquery days to store from 1-st passed argument or strictly hardcode it, uncomment one to use
STORE_DAYS=${1:? "Usage ${0##*/} X, where X - count of daily archives to store"}
# STORE_DAYS=7
function removeOlderThanDays() {
# Make some temp files to store intermediate data
LIST=`mktemp`
DELLIST=`mktemp`
# Connect to ftp get file list and store it into temp file
${LFTP} << EOF
open ${FTP_USER}:${FTP_PASS}@${FTP_HOST}
cd ${FTP_PATH}
cache flush
cls -q -1 --date --time-style="+%Y%m%d" > ${LIST}
quit
EOF
# Print obtained list, uncomment for debug
# echo "File list"
# cat ${LIST}
# Delete list header, uncomment for debug
# echo "Delete list"
# Let's find date to compare
STORE_DATE=$(date -d "now - ${STORE_DAYS} days" '+%Y%m%d')
while read LINE; do
if [[ ${STORE_DATE} -ge ${LINE:0:8} && "${LINE}" != */ ]]; then
echo "rm -f "${LINE:9}"" >> ${DELLIST}
# Print files which are subject to deletion, uncomment for debug
#echo "${LINE:9}"
fi
done < ${LIST}
# More debug strings
# echo "Delete list complete"
# Print notify if list is empty and exit.
if [ ! -f ${DELLIST} ] || [ -z "$(cat ${DELLIST})" ]; then
echo "Delete list doesn't exist or empty, nothing to delete. Exiting"
exit 0;
fi
# Connect to ftp and delete files by previously formed list
${LFTP} << EOF
open ${FTP_USER}:${FTP_PASS}@${FTP_HOST}
cd ${FTP_PATH}
$(cat ${DELLIST})
quit
我已经处理过几次这种事情了。
如何通过bash脚本连接到ftp服务器
在bash脚本中自动向ftp提供命令
bash ftp上传-记录的事件
最好尽可能使用scp
和/或ssh
,尤其是如果可以使用公钥设置无密码访问。否则,我推荐一种更健壮的语言,如Python或Perl,它可以让您单独检查这些步骤的返回代码并做出相应的响应。