0

I am busy writing a bash script that can delete a file according to the date in a file name for example xxxxxxxxx140516.log. It should delete the file a day after the 16 of May 2014. I would like the script to read the file from character 25 because this is were the date start and it should do regular checks to see if there are any old files. Current my script looks like this:

#!/bin/bash 
rm *$(date -d "-1 day" +"%y%m%d")*

The problem with this script is that if the computer is not up and running for a couple of days it will not delete old files that is past the date and it does not start on character 25. Please help, Thanks

1
  • I don't know what possibilities lay in xxxxxxx, but I would replace that last * with .log to avoid accidental deletion of files that have the same date string somewhere in the xxxxxx too. Commented May 16, 2014 at 21:34

2 Answers 2

1
for day in {1..7}; do
    rm -f ????????????????????????$(date -d "-$day day" +"%y%m%d").log
done

This will allow for the script not running up to a week; you can change the range to handle longer periods.

There are 24 ? characters in the wildcard, so it will find the date starting at character 25.

The -f option keeps rm from printing an error message if no matching files are found. Warning: it also prevents it from asking for confirmation if you don't have write permission to the file.

the notation {start..end} expands into a sequence of numbers from start to end, so {1..10} would be short for 1 2 3 4 5 6 7 8 9 10. You can also use {char1..char2} to get a sequence of characters, e.g. {a..d} is short for a b c d.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi Barmar, what does: ' for day in {1..7}; do ' I am a bit new to bash, thanks
I added an explanation of the brace notation.
0

If you want, you can purge such log files using the timestamps of those files as follows:

find <path_to_logs_dir> -mtime +0 -exec rm {} \;

The above command will purge any files older than today. Please note that this command doesn't specifically look for log files of any format as such. I am just assuming here that the log directory only contains the log files.

Further you can filter out log files as below ->

find <path_to_logs_dir> -name "*.log" -type f -mtime +0 -exec rm {} \;

"-type f" ensures it lists only files and not directories.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.