Monitor several directories for specific files' creation, every 10s

OS: Ubuntu 22.04 LTS.

Many posts deal with file monitoring. One in particular is of interest and based on inotifywait, but I don’t know how to modify it for my purpose.

Objective: to monitor $HOME/{Documents/,Downloads/,Archive/} for link files *.lnk as they are created. Those files are created every time I use Word in Wine to create, save, open or do anything with a document. Dozens *.lnk files can be created in mere minutes. This issue is killing me.

I am willing to learn but can’t translate generic examples into what I need for lack of knowledge. I know how to run a script in a plain file, but if there’s anything special I should know in this regard, please let me know. Tx in advance.

Asked By: Trynn

||

You need to write this small script in a file using your terminal. I assume you are using the bash shell since you are beginning, and on Ubuntu. Let us know if it is otherwise.

$ touch notify_links
$ chmod u+x notify_links
$ cat notify_script
#!/usr/bin/env bash
inotifywait -mr -e moved_to,create "$HOME"/{Documents,Downloads,Archive} |
while read directory action file; do
    if [[ "$file" =~ .lnk$ ]]; then
        echo rm -f "$file"
    fi
done

Run this script. To do so, just issue (in terminal) the following command notify_links in terminal.

Once satisfied by what you see appearing on terminal display, remove the echo in the script line: echo rm -f "$file" to leave only rm -f "$file".

EDIT 1 per @ilkkachu’s comment in order to specialize monitoring to three directories/folders instead of the complete $HOME subtree.

EDIT 2 per @Paul_Pedant’s comment, in order to run this automatically every 10 seconds as soon as your boot process is finished, edit your /etc/crontab file with crontab -e to include:

 * * * * * $USER for i in $(seq 5); do /usr/bin/find $HOME -name "*.lnk" -delete; sleep 10; done

EDIT 3 for faster result and lesser resource usage, you’ll want to search only the directories that you mentionned in OP. The following will search their subtrees:

 * * * * * $USER for i in $(seq 5); do /usr/bin/find "$HOME"/{Documents,Downloads,Archive} -name "*.lnk" -delete; sleep 10; done

In order to prevent find from recursing down the subtrees, add the following option -maxdepth 1 before -name "*.lnk" in the find command.

Answered By: Cbhihe
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.