Linux Shell 脚本 - 查找今天修改的文件,创建目录,并将它们移动到那里

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7235449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 05:56:10  来源:igfitidea点击:

Shell script - Find files modified today, create directory, and move them there

linuxbashshellfilesystems

提问by Everaldo Aguiar

I was wondering if there is a simple and concise way of writing a shell script that would go through a series of directories, (i.e., one for each student in a class), determine if within that directory there are any files that were modified within the last day, and only in that case the script would create a subdirectory and copy the files there. So if the directory had no files modified in the last 24h, it would remain untouched. My initial thought was this:

我想知道是否有一种简单而简洁的方法来编写一个 shell 脚本,该脚本将遍历一系列目录(,一个班级中的每个学生一个),确定该目录中是否有任何文件被修改最后一天,只有在这种情况下,脚本才会创建一个子目录并将文件复制到那里。因此,如果该目录在过去 24 小时内没有修改任何文件,它将保持不变。我最初的想法是这样的:

#!/bin/sh
cd /path/people/ #this directory has multiple subdirectories

for i in `ls`
do
   if find ./$i -mtime -1  -type f  then 
     mkdir ./$i/updated_files
     #code to copy the files to the newly created directory
   fi
done

However, that seems to create /updated_files for all subdirectories, not just the ones that have recently modified files.

但是,这似乎为所有子目录创建了 /updated_files,而不仅仅是最近修改过文件的子目录。

采纳答案by thiton

Heavier use of findwill probably make your job much easier. Something like

大量使用find可能会使您的工作更轻松。就像是

find /path/people -mtime -1 -type f -printf "mkdir --parents %h/updated_files\n" | sort | uniq | sh 

回答by Mark Borgerding

The problem is that you are assuming the findcommand will fail if it finds nothing. The exit code is zero (success) even if it finds nothing that matches.

问题是您假设find命令如果什么也没找到就会失败。即使没有找到匹配的内容,退出代码也为零(成功)。

Something like

就像是

UPDATEDFILES=`find ./$i -mtime -1  -type f`
[ -z "$UPDATEDFILES" ] && continue
mkdir ...
cp ...
...