How to realize periodic log migration by using find command in linux
How to use the find command to achieve regular log migration in linux, many novices are not very clear about this, in order to help you solve this problem, the following small series will explain in detail for everyone, there are people who need this can learn, I hope you can gain something.
1. Find command format
find pathname --options [-exec -print -ok ..]
Second, find command parameters
pathname: path to directory found by find command
-print: find command prints matching files to standard output
-exec: The find command executes the shell command given by this parameter on the matching file. Format: command {} \;
-ok: similar to exec
Third, find command options
-name: Search by file name
-perm: Find by file permissions
-user: Search by user of file
-group: Find by user group of file
-type: Find a certain type of file
b -block device file
d --Contents
c --Character device file
p --pipe file
l --Symbolic link file
f --General documents
-mtime: Find files by their change time
-n --Indicates that the file was changed within n days of the present
+n --Indicates that the file was changed n days ago
IV. Log Migration Script
Use the mtime parameter of the find command to migrate log files from 2 weeks ago to the specified directory.
The code is as follows:
#!/ bin/bash
# site: www.yisu.com
#1. Standard Definition
backup_dir="/backup/log"
keep_days=14
week_num=`date +%W`
flag=`expr $week_num % 2`
#2. Need to migrate directories
test1="/var/log/nginx/test1"
migrate_dir=($test1)
#3. Migrate backups every two weeks
if [ $flag -eq 1 ];then
for dir in ${clean_dir[*]}
do
if [ -d $dir ]; then
#Build migration directory
if [ ! -d $backup_dir$dir ];then
mkdir -p $backup_dir$dir
fi
#File migration
for file in `find $dir -type f -mtime +$keep_days -exec ls {} \;`
do
mv $file $backup_dir$dir
done
fi
done
fi
Crontab executes log migration scripts every two weeks
The code is as follows:
#Log Periodic Migration Script
0 4 * * 7/2 /home/wangzhengyi/scripts/clean-scripts/migrate.sh
Search by file size
The size parameter of the find command can be searched by file size. The size options are as follows:
For example, to find files larger than 10k in a specified directory, command:
Did reading the above help you? If you still want to have further understanding of related knowledge or read more related articles, please pay attention to the industry information channel, thank you for your support.