Execute a command when add a new file in folder

I am not sure weather it's possible or not. I am looking for a script/command that will execute a command or run a scripts when I will add a file in a folder.

For instance:

I am practicing bash scripting. After writing a bash script, I have to make my script file to a executable using this command chmod +x filename.sh . All my scripts has stored in a folder named BASH . So, when I add a new .sh file in that folder, I want a command/script to run which will make my .sh file executable.

How to do it?


Solution 1:

You can use inotifywait. To apply chmod +x to every file written in directory BASH, keep the following script running:

#!/bin/bash
dir=BASH
inotifywait -m "$dir" -e close_write --format '%w%f' |
    while IFS=' ' read -r fname
    do
        [ -f "$fname" ] && chmod +x "$fname"
    done

If you are curious, you can see all that inotifywait can tell about what is happening in directory bash by running:

inotifywait -m BASH

For more information, see man inotifywait.

To use inotifywait, you may first need to install inotify-tools: run apt-get install inotify-tools.