Artifactory中curl误删Backup目录,如何删除7天前日期文件夹?
It looks like your original command wiped out the entire Backup directory because your $Date variable wasn't correctly generating the 7-day-old date (or was empty), so Artifactory interpreted the request as deleting the root Backup path. Let's fix this with targeted shell commands that work seamlessly in Jenkins:
Step 1: Generate the Correct 7-Day-Old Date String
First, you need to match the date format exactly to how your Date folders are named in Artifactory (e.g., YYYY-MM-DD or YYYYMMDD). Use the right command for your Jenkins agent's OS:
For Linux/macOS Agents:
- If folders use
YYYY-MM-DDformat:# Linux (GNU date) SEVEN_DAYS_AGO=$(date -d "7 days ago" +%Y-%m-%d) # macOS (BSD date) SEVEN_DAYS_AGO=$(date -v -7d +%Y-%m-%d) - If folders use
YYYYMMDDformat:# Linux SEVEN_DAYS_AGO=$(date -d "7 days ago" +%Y%m%d) # macOS SEVEN_DAYS_AGO=$(date -v -7d +%Y%m%d)
For Windows PowerShell Agents:
YYYY-MM-DDformat:$SevenDaysAgo = (Get-Date).AddDays(-7).ToString("yyyy-MM-dd")YYYYMMDDformat:$SevenDaysAgo = (Get-Date).AddDays(-7).ToString("yyyyMMdd")
Step 2: Run the Targeted Delete Command
Artifactory requires the ?recursive=true parameter to delete non-empty folders. Use this precise command to only remove the specific dated folder:
Linux/macOS:
# Replace user/pass with your actual Artifactory credentials curl -k -u user:pass -X DELETE "https://artifactory.test.com/artifactory/Backup/${SEVEN_DAYS_AGO}?recursive=true"
Windows PowerShell:
$url = "https://artifactory.test.com/artifactory/Backup/$SevenDaysAgo`?recursive=true" $cred = New-Object System.Management.Automation.PSCredential("user", (ConvertTo-SecureString "pass" -AsPlainText -Force)) Invoke-RestMethod -Uri $url -Method Delete -Credential $cred -SkipCertificateCheck
Step 3: Add a Safety Check (Optional but Recommended)
To avoid accidental deletions if the dated folder doesn't exist, add a pre-check to verify the folder exists first:
Linux/macOS Safety Check:
# Check if the target folder exists via a HEAD request if curl -k -u user:pass -I "https://artifactory.test.com/artifactory/Backup/${SEVEN_DAYS_AGO}/" | grep -q "200 OK"; then echo "Deleting old backup folder: Backup/${SEVEN_DAYS_AGO}" curl -k -u user:pass -X DELETE "https://artifactory.test.com/artifactory/Backup/${SEVEN_DAYS_AGO}?recursive=true" else echo "Backup/${SEVEN_DAYS_AGO} doesn't exist — skipping deletion." fi
This ensures you only delete the intended folder, never the entire Backup directory.
内容的提问来源于stack exchange,提问作者Vidisha

