Home > OS >  Delete files older than n days from Jenkins workspace
Delete files older than n days from Jenkins workspace

Time:01-12

This is a repeated question for sure. Apologies for that

My usecase is exact the one in this shared SO question: Delete files older than X days in Jenkins workspace

but the solution hasn't worked for me. I tried adding a post build step that is mentioned in the blog.

${WORKSPACE}/*.xml -type f -mtime  6 -delete 

Though I have given all executable permissions for the workspace directory I am ended up with permission denied error. I want to delete .xml files which reside in Jenkins for more than 6 days. Is the script correct?

CodePudding user response:

You can use the find and rm commands to delete files older than a certain number of days from the Jenkins workspace. Here's an example of how you can do this:

find ${WORKSPACE} -type f -mtime  30 -exec rm {} \;

This command will find all files in the $WORKSPACE directory that have a modification time older than 30 days and delete them.

You can replace 30 with the number of days that you want to use as the cutoff.

Alternatively, you can use the following command

find ${WORKSPACE} -mtime  30 -exec rm -f {}  

which is more efficient as it will reduce the number of exec syscalls

You can put this command in a shell script and then execute the script as a build step in Jenkins.

To do that:

  1. Go to your Jenkins job configuration
  2. Scroll down to "Build" section
  3. Click on "Add build step"
  4. Select "Execute shell"
  5. Paste the command: save

You can also schedule the deletion as a cron job in the server where Jenkins is running, to run on a regular schedule, so you don't need to add build step to your job configuration.

Please note that this command will delete files permanently and without confirmation. Make sure to test the command on a small scale before running it in the main workspace, and to have a backup of your data.

  • Related