Search code examples
linuxdirectoryscriptingmoveinotify

Multiple inotify events in one script


I'm trying to write a bash script (which is installed as a service) to watch multiple directories and move any files that are created in that directory to another directory. For example, I want to move any files created in /home/test/directory1 to /opt/directory1 but I also want to move any files created in /home/test/directory2 to /opt/directory2 but all in one script as a running service. This is my script so far;

#/bin/bash

directory=/home/test/directory1
archive=/home/test/archive
target=/opt/directory1

inotifywait -m "$directory" --format '%w%f' -e create |
    while read file; do
        cp "$file" "$archive"
        mv "$file" "$target"
    done

Any pointers would be greatly appreciated, Thanks.


Solution

  • Sure, that can be done, with a little bit of extra logic; caveat: this assumes that any of the target directories exist in both /home/test and under /opt and that their names match.

    #!/bin/bash
    # we use an array to store the watched directories
    directories=(/home/test/directory5 /home/test/directory6)
    archive="/home/test/archive"
    target="/opt"
    inotifywait -m --format '%w%f' -r -e create "${directories[@]/#/}" | 
        while read spotted; 
            do
                cp "${spotted}" "$archive"
                mv "${spotted}" "$( echo ${spotted}|awk 'BEGIN{FS=OFS="/"}{print "/opt",$(NF-1),$NF }')"
            done
    

    Another observation: should a file of the same name be created in either of your directories the target in archive will be overwritten. You may want to think about that.