Automatically clean up log files in A and B machines
- [Shell requirements] There
are more than 300 machines of the two types. Write a script to automatically clean up the log files in the two types of machines.
The log storage path for type A machines is uniform, and the log file storage path for type B machines needs to be matched with * (because this directory has other files besides log files, which cannot be deleted, look at *.log when matching)
Type A storage path: /opt/cloud/log/ Requirement: delete logs 7 days ago
Type B storage path: /opt/cloud/instances/ Requirement: delete logs 15 days ago
-
[Shell analysis]
1. A general script needs to be written, which means that the script can be run regardless of whether it is placed on a class A machine or a class B machine.
2. It is necessary to determine whether it is a type A or a type B machine. You can determine the existence of the directory /opt/cloud/log/ or /opt/cloud/instances/ to determine which type of machine it is.
3. Find directly for a type A machine That’s all, but for class B machines, it’s a little cumbersome to find -name ".log".
4. Find the parameters of the day before find
5. After finding the log file, pass it to the rm command to delete it. -
[Shell configuration]
aPATH="/opt/cloud/log/" bPATH="/opt/cloud/instances/" if [ -d $aPATH ];then find $aPATH -mtime -7 -name "*.log" -exec rm -rf {} \; echo "$?" && echo "日志文件已删除" elif [ -d $bPATH ];then find $bPATH -mtime -15 -name "*.log" -exec rm -rf {} \; echo "日志文件已删除" Fi
-
[Shell test]
You can create a ".log" file in categories A and B, execute the script, and delete it
(note that the file format in the directory is .log; the log file creation time is a few days ago and a few days later (for example : +7 seven days ago; -7 seven days later; -7 built today))