I'm new to bash, I have a task to delete all files older than 30 days, I can figure this out based on the files name Y_M_D.ext
2019_04_30.txt
.
I know I can list all files with ls
in a the folder containing the files. I know I can get todays date with $ date
and can configure that to match the file format $ date "+%Y_%m_%d"
I know I can delete files using rm
.
How do I tie all this together into a bash script that deletes files older than 30 days from today?
In pseudo-python code I guess it would look like:
for file in folder:
if file.name to date > 30 day from now:
delete file
I am by no means a systems administrator, but you could consider a simple shell script along the lines of:
Note that this is will probably be considered a "layman" solution by a professional. Maybe this is handled better by
awk
, which I am unfortunately not accustomed to using.For delete file older than X days you can use this command and schedule it in
/etc/crontab
find /PATH/TO/LOG/* -mtime +10 | xargs -d '\n' rm
or
find /PATH/TO/LOG/* -type f -mtime +10 -exec rm -f {} \
Here is another solution to delete log files older than 30 days:
allows to include multiple directory where to delete files
we fill the var: we'r doing a search (in the directory provided) for files which are older than 30 days and whose name contains at least .log. Then counts the number of files.
we then check if there is a result other than 0 (posisitive), if yes we delete