Bash script, watch folder, execute command

后端 未结 12 1342
小鲜肉
小鲜肉 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条回答
  •  旧时难觅i
    2020-12-04 09:14

    METHOD 1:

    #!/bin/sh
    
    check() {
        dir="$1"
        chsum1=`digest -a md5 $dir | awk '{print $1}'`
        chsum2=$chsum1
    
        while [ $chsum1 -eq $chsum2 ]
        do
            sleep 10
            chsum2=`digest -a md5 $dir | awk '{print $1}'`
        done
    
        eval $2
    }
    
    check $*
    

    This script takes in two parameters [directory, command]. Every 10 seconds the script executes check() to see it the folder has changed. If not it sleeps and the cycle repeats.

    In the event that the folder has changed, it evals your command.

    METHOD 2:
    Use a cron to monitor the folder.

    You'll have to install incron:

     sudo apt-get install incron
    

    And then your script will look something like this:

    #!/bin/bash
    eval $1
    

    (You won't need to specify the folder since it will be the job of the cron to monitor the specified directory)

    A full, working example can be found here:

    http://www.errr-online.com/index.php/2011/02/25/monitor-a-directory-or-file-for-changes-on-linux-using-inotify/

提交回复
热议问题