As a follow up to a previous question, linkedhere, I have revised the code and developed what I believe to be a better solution.
In summary, the script should backup all files in a particular directory, and assign them to a particular zip file based on their modification dates. This should only occur for files modified yesterday and older, and skip files with the ".zip" extension.
Please let me know if their are any improvements that you would make? From testing the code, it has been working with no issues:
#!/bin/bashyestdayend=$(date --date="yesterday" +"%Y-%m-%d 23:59:59")path=/path/to/dirfilelist=$(find $path -maxdepth 1 ! \( -name "*.zip" \) -type f ! -newermt "$yestdayend")for file in $filelistdo moddate=$(stat -c %y $file | cut -d " " -f 1) if zip -rv $path/"logbackup-"$moddate.zip $file; then rm $file fidone1 Answer1
Saving the output offind in a variable and looping over it is not a good idea in general: filenames with white-space (space, tab, newline) will be split, so the loop will not work on them.
It would be a little bit better to use awhile loop instead:
find ... | while read filedo # ...doneBut this is still not great, as it won't protect you from newlines.But for your use case, it might be good enough.For a more robust solution,see this other post.
The\( ... \) is pointless here:
find $path -maxdepth 1 ! \( -name "*.zip" \) -type f ! -newermt "$yestdayend"
This is the same, but shorter and simpler:
find $path -maxdepth 1 ! -name "*.zip" -type f ! -newermt "$yestdayend"It's a bit odd to quote "logbackup-" here:
if zip -rv $path/"logbackup-"$moddate.zip $file; then
Literal strings like that don't need quoting in Bash.On the other hand, it would be good to quote$path:
if zip -rv "$path"/logbackup-$moddate.zip $file; thenYou mustlog in to answer this question.
Explore related questions
See similar questions with these tags.
