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

10,473

Solution 1

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 

Solution 2

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 ...
...
Share:
10,473
Everaldo Aguiar
Author by

Everaldo Aguiar

Updated on June 05, 2022

Comments

  • Everaldo Aguiar
    Everaldo Aguiar about 2 years

    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:

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

  • Everaldo Aguiar
    Everaldo Aguiar almost 13 years
    Thanks. This statement works fine for creating the subfolders :) How would I incorporate a statement that copies multiple recently modified files into the folder just created? Does find give me a flag holding the list of files found?
  • cili
    cili about 11 years
    @Everaldo Aguiar: Can you post the solution here, please?