我有一个远程文件列表。我可以使用curl
或访问这些文件Ansible
。该列表如下所示:
sqldbd_12_30_2020_14_29_30.tar.gz
sqldbd_12_30_2020_14_52_32.tar.gz
sqldbd_12_31_2020_14_57_49.tar.gz
sqldbp_12_31_2020_16_00_40.tar.gz
sqldbd_01_01_2021_16_29_57.tar.gz
sqldbd_01_02_2021_18_00_35.tar.gz
sqldbd_01_03_2021_20_00_33.tar.gz
sqldbd_01_03_2021_22_00_37.tar.gz
sqldbf_01_04_2021_00_00_37.tar.gz
sqldbc_01_06_2021_02_00_33.tar.gz
日期格式为:(%m_%d_%Y_%H_%M_%S
自定义日期格式)。我只想curl DELETE
对超过 7 天的文件执行。此刻我设法写下:
#!/bin/bash
auth_token=$1
storage_url=$2
compare_date=$(date -d '-7 days' '+%m_%d_%Y_%H_%M_%S')
for line in $(cat backup_list.txt); do
timestamp=$(echo "${line%.*.*}" | cut -d '_' -f 2,3,4,5,6,7)
if [[ "$timestamp" < "$compare_date" ]]; then
curl -k -X DELETE "${storage_url}/sql_backups/$line" -H "X-Auth-Token: ${auth_token}"
fi
done
不幸的是,这并没有按预期工作,最终所有文件都被删除。我想我可以强制备份脚本以不同的格式创建日期字符串。
答案1
如果将 vars 转换为 yyyymmddhhmmss 或 posix 时间戳,则比较将起作用
#!/bin/bash
auth_token=$1
storage_url=$2
# posix epoch
compare_date=$(date -d '-7 days' +'%s')
for line in $(cat backup_list.txt); do
timestamp=$(echo "${line%.*.*}" | cut -d '_' -f 2,3,4,5,6,7)
# YYYYMMDD hh:mm:ss
datetime="${timestamp:6:4}${timestamp:0:2}${timestamp:3:2} ${timestamp:11:2}:${timestamp:14:2}:${timestamp:17:2}"
# posix epoch
timestamp=$(date -u -d "$datetime" +'%s')
if [[ "$timestamp" < "$compare_date" ]]; then
curl -k -X DELETE "${storage_url}/sql_backups/$line" -H "X-Auth-Token: ${auth_token}"
fi
done