Background: I have a backup directory/home/kzy/bakup, which backs up some information every day. As the days go by, this folder is getting bigger, and finally the disk is full ...
Requirements: Automatically delete the oldest 30 days of files in this folder when the disk share exceeds 80%, but keep files for at least the last 7 days.
Code:
As follows. (Code for a whole day ah, just put so little code out AH!!!) Shell programming Super Rotten AH!!! Even basic grammar must be checked!!! All kinds of error notes!!! Why is my level so rotten!!!!!! )
#!/bin/bash#monitor available disk spacedir='/home/kzy/bakup'rm_date= -least_retain_date=7Threshold= theSPACE=$(DF-p|sed-N'/\/$/p'|gawk '{print $}'|sed 's/%//') Cur_date=$(Date "+%y-%m-%d%h:%m:%s")Echo "========== $cur _date start=========="if[$SPACE-GE $threshold] ThenOldest_file=$(ls-alt|Tail-1|gawk '{print $9}') oldest_date=$(Stat$oldest _file|grep^modify|gawk '{print$2}'|sed 's/-//g') Cur_time=$(Date+%s) oldest_time=$(Date-D ${oldest_date} +%s) diff_time=$ ($cur _time-$oldest _time)) Diff_date=$ (($diff _time/86400)) Remain_date=$least _retain_dateif[$ ($diff _date-$rm _date))-ge $least _retain_date] Thenremain_date=$(Expr$diff _date-$rm _date)ficmd="Find $dir-mtime + $remain _date-exec rm-rvf {} \;" Echo "Space is the use of more than $threshold%! Rmove some tmp files!" Echo$cmdEcho "---detail---"eval $cmdElse Echo "$SPACE% used!"fiEcho "=======end======="
Keep the logs in the crontab and run every day.
------------------------------------Detail Split Line-----------------------------------
Now, let's take a look at all the knowledge I've learned.
1. After I write a simple if statement, the error syntax error: "FI" unexpected (expecting "then"
cause : I was writing code under Windows and then I ran under Linux. Because the format of the two platforms is different, the code edited under Windows will have special characters, so the run fails.
fix : Install Dos2unix under Linux, run
Dos2unix Monitor_disk. SH
The following is the name of the file to convert.
2. View disk Usage DF command
DF -HP
Results
Filesystem Size used Avail use%mounted Onudev 973M0973M0% /Devtmpfs 199M 26M 174M -% /Run/DEV/SDA1 19G 14G4.3G the% /tmpfs 992M 308K 992M1%/dev/Shmtmpfs5.0M 4.0K5.0M 1%/run/Locktmpfs 992M0992M0%/sys/fs/Cgroupcgmfs 100K0100K0%/run/cgmanager/Fsnone 992M2.6M990M1%/tmp/guest-Grytrhtmpfs 199M 68K 199M1%/run/user/123tmpfs 199M 76K 199M1%/run/user/ +/dev/sr0 71M 71M0 -%/media/zhuwenqian/vmware Tools
Parameter description:
-H: Displayed in M, G and other units for easier reading
-P: If there is no-P, the result is displayed in a branch when the file path is too long, which makes it difficult to use script processing. Plus-P guarantees no line break.
"Linux" monitors disk conditions and automatically deletes backup files