Bash script, watch folder, execute command

后端 未结 12 1349
小鲜肉
小鲜肉 2020-12-04 08:57

I am trying to create a bash script with 2 parameters:

  • a directory
  • a command.

I want to watch the

12条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 09:12

    I can’t believe nobody posted this yet.

    First make sure inotify-tools are installed.

    Then use them like this:

    logOfChanges="/tmp/changes.log.csv" # Set your file name here.
    
    # Lock and load
    inotifywait -mrcq $DIR > "$logOfChanges" &
    IN_PID=$$
    
    # Do your stuff here
    ...
    
    # Kill and analyze
    kill $IN_PID
    cat "$logOfChanges" | while read entry; do
       # Split your CSV, but beware that file names may contain spaces too.
       # Just look up how to parse CSV with bash. :)
       path=... 
       event=...
       ...  # Other stuff like time stamps?
       # Depending on the event…
       case "$event" in
         SOME_EVENT) myHandlingCode path ;;
         ...
         *) myDefaultHandlingCode path ;;
    done
    

    Alternatively, using --format instead of -c on inotifywait would be an idea.

    Just man inotifywait and man inotifywatch for more infos.

提交回复
热议问题