Dimitri Auxio
Dimitri Auxio

Reputation: 13

Linux Find and execute

I need to write a Linux script where it does the following: Finding all the .ear and .war files from a directory called ftpuser, even the new ones that are going to appear there and then execute one command that it produces some reports. When the command finishes then those files need to be moved to another directory.

Below I think that I have found how the command starts. My question is does anyone know how to find the new entries on the directory and then execute the command so I can get the report?

find /directory -type f -name "*.ear" -or -type f -name "*.war" 

Upvotes: 1

Views: 857

Answers (2)

Justin Sane
Justin Sane

Reputation: 66

This might also help: Monitor Directory for Changes

If it is not time-critical, but you are not willing to start the script (like the one suggested by devnull) manually after each reboot or something, I suggest using a cron-job.

You can set up a job with

crontab -e

and appending a line like this:

* * * * * /usr/bin/find /some/path/ftpuser/ -type f -name "*.[ew]ar" -exec sh -c '/path/to/your_command $1 && mv $1 /target_dir/' _ {} \;

This runs the search every minute. You can change the interval, see https://en.wikipedia.org/wiki/Cron for an overview. The && causes the move to be only executed if your_command succeeded. You can check by running it manually, followed by

echo $?

0 means true or success. For more information, see http://tldp.org/LDP/abs/html/exit-status.html

Upvotes: 2

devnull
devnull

Reputation: 123478

It seems that you'd want the script to run indefinitely. Loop over the files that you find in order to perform the desired operations:

while : ; do
  for file in $(find /directory -type f -name "*.[ew]ar"); do
    some_command "${file}"           # Execute some command for the file
    mv "${file}" /target/directory/  # Move the file to some directory
  done
  sleep 60s                          # Maybe sleep for a while before searching again!
done

Upvotes: 2

Related Questions