简体   繁体   中英

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

I was wondering if there is a simple and concise way of writing a shell script that would go through a series of directories, ( ie , 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:

#!/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.

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

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

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

Something like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM