Anshul Agarwal
Anshul Agarwal

Reputation: 31

Run a script on all recently modified files in bash

I would like to:

  1. Find latest modified file in a folder
  2. Change some files in the folder
  3. Find all files modified after file of step 1
  4. Run a script on these files from step 2

This this where I've end up:

#!/bin/bash
var=$(find /home -type f -exec stat \{} --printf="%y\n" \; |
     sort -n -r |
     head -n 1)
echo $var
sudo touch -d $var /home/foo
find /home/ -newer /home/foo

Can anybody help me in achieving these actions ?

Upvotes: 2

Views: 387

Answers (1)

Nasr
Nasr

Reputation: 2632

Use inotifywait instead to monitor files and check for changes

inotifywait -m -q -e modify --format "%f" {Path_To__Monitored_Directory}

Also, you can make it output to file, loop over it's contents and run your script on every entry.

 inotifywait -m -q -e modify --format "%f" -o {Output_File} {Path_To_Monitored_Directory}

sample output:

 file1
 file2

Example

We are monitoring directory named /tmp/dir which contains file1 and file2. The following script which monitor the whole directory and echo the file name:

#!/bin/bash

while read ch
do
    echo "File modified= $ch"
done < <(inotifywait -m -q -e modify --format "%f" /tmp/dir)

Run this script and modify file1 echo "123" > /tmp/dir/file1, the script will output the following:

File modified= file1

Also you can look at this stackoverflow answer

Upvotes: 1

Related Questions