Home > other >  Delete files that are 5 days old using bash script
Delete files that are 5 days old using bash script

Time:04-16

I currently use a command that searches a directory and deletes 5 day old files.

find /path/to/files* -mtime 5 -exec rm {} \;

I run it from the command line and it works fine. But when I put it in a .sh file it says find /path/to/files*: No such file or directory.

There is only two lines in the shell script:

#! /usr/bin/env bash

find /path/to/files* -mtime  5 -exec rm {} \;

How can I rewrite the script so that it works? `

CodePudding user response:

The error happens if there are currently no files matching the wildcard, presumably because none have been created since you deleted them previously.

The argument to find should be the directory containing the files, not the filenames themselves, since find will automatically search the directory. If you want to restrict the filenames, use the -name option to specify the wildcard.

And if you don't want to go into subdirectories, use the -maxdepth option.

find /path/to -maxdepth 1 -type f -name 'files*' -mtime  5 -delete

CodePudding user response:

This works:

#! /usr/bin/env bash

find /home/ubuntu/directory -type f -name 'filename*' -mtime  4 -delete

Here is an example:

find /home/ubuntu/processed -type f -name 'output*' -mtime  4 -delete
  •  Tags:  
  • bash
  • Related