Ubuntu – WSL – A Bash line to show when a folder’s contents update

automationbashcommand linescriptswindows-subsystem-for-linux

I'm looking for a bash script that will detect when a file enters a specific folder. Basically I want to eventually make a script that will detect when a file enters a certain folder on my desktop (using windows with wsl), add .png to the end of the file name (long story, just need that to happen), and then move to another file on my desktop. I have something to rename the files, as a friend made it and we worked together to troubleshoot it

for i in /[directory here] ; do mv "$i" "$i.png" ; done

Now I just need to automate it. I don't want to bother him more, since he has already done so much, and I am too new to Ubuntu to understand exactly what to do

Best Answer

You can use inotify-tools

To install it, run the following command in the terminal:

sudo apt install inotify-tools

To use it to serve your purpose, please follow these steps:

  1. Create and edit a script file in your home directory by running the following command in the terminal:

    nano ~/File_Monitor.sh

  2. Copy and paste the following code into the editor replacing PATH_TO_DIRECTORY with the full path of the directory you want to monitor:

#!/bin/bash
inotifywait -m PATH_TO_DIRECTORY -e create |
    while read path action file;
        do
                echo "$path$file was created"
                mv "$path$file" "$path$file.png"
                echo "and renamed to $path$file.png"
        done

  1. Save the script file and exit the editor by pressing Ctrl + X then press Y.

  2. Make the script file executable by running the following command in the terminal:

    chmod +x ~/File_Monitor.sh

  3. Run the script by running the following command in the terminal:

    bash ~/File_Monitor.sh

Done, all new files added to the monitored directory will be renamed to Original_File_Name.png.


Notice:

If you cannot get inotify-tools installed for any reason, you can replace the code in step 2 with the following code also changing PATH_TO_DIRECTORY with the full path of the directory you want to monitor:

#!/bin/bash

while true
do
       sleep 1
       find PATH_TO_DIRECTORY -type f ! -name "*.*" -exec mv {} {}.png \;
done

It will get the job done.