user3938558
user3938558

Reputation: 63

Create a bash script that runs and updates a log whenever a file is deleted

I am new to bash scripting and I have to create a script that will run on all computers within my group at work (so it's not just checking one computer). We have a spreadsheet that keeps certain file information, and I am working to automate the updating of that spreadsheet. I already have an existing python script that gathers the information needed and writes to the spreadsheet.

What I need is a bash script (cron job, maybe?) that is activated anytime a user deletes a file that matches a certain extension within the specified file path. The script should hold on to the file name before it is completely deleted. I don't need any other information besides the name.

Does anyone have any suggestions for where I should begin with this? I've searched a bit but not found anything useful yet.

It would be something like:

 for folders and files in path:
      if file ends in .txt and is being deleted:
            save file name

Upvotes: 3

Views: 461

Answers (1)

John1024
John1024

Reputation: 113834

To save the name of every file .txt deleted in some directory path or any of its subdirectories, run:

inotifywait -m -e delete --format "%w%f" -r "path" 2>stderr.log | grep '\.txt$' >>logfile

Explanation:

  • -m tells inotifywait to keep running. The default is to exit after the first event

  • -e delete tells inotifywait to only report on file delete events.

  • --format "%w%f" tells inotifywait to print only the name of the deleted file

  • path is the target directory to watch.

  • -r tells inotifywait to monitor subdirectories of path recursively.

  • 2>stderr.log tells the shell to save stderr output to a file named stderr.log. As long as things are working properly, you may ignore this file.

  • >>logfile tells the shell to redirect all output to the file logfile. If you leave this part off, output will be directed to stdout and you can watch in real time as files are deleted.

  • grep '\.txt$' limits the output to files with .txt extensions.

Mac OSX

Similar programs are available for OSX. See "Is there a command like “watch” or “inotifywait” on the Mac?".

Upvotes: 2

Related Questions