Bash script, watch folder, execute command

Viewed 55207

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

  • a directory
  • a command.

I want to watch the directory parameter for changes: when something has been changed the script should execute the command.

I'm running MacOS, not Linux; any pointers or external resources would greatly help as I have see that this is difficult to achieve. Really OI am trying to mimic SASS's watch functionality.

#!/bin/bash

#./watch.sh $PATH $COMMAND

DIR=$1  

ls -l $DIR > $DIR/.begin
#this does not work
DIFFERENCE=$(diff .begin .end)

if [ $DIFFERENCE = '\n']; then
    #files are same
else
    $2
fi 

ls -l $DIR > $DIR/.end
13 Answers

Radek's answer "sort of" worked for me (OSx) but it slows down my terminal. I made some modifications on it and here's what I think works for me:

#!/bin/bash

daemon() {
    chsum1=""
    targetFolder=path-to-target-folder

    while [[ true ]]
    do
        chsum2=`find ${targetFolder} -type f | xargs stat -f "%m" | md5`
        if [[ $chsum1 != $chsum2 ]] ; then
            # echo the date to indicate we are updating   
            date
            ./do-something.sh
            # tracks the check-sum
            chsum1=$chsum2
        fi
        # sleep for 2 secs
        sleep 2
    done
}

daemon 

The meat is in:

chsum2=`find ${targetFolder} -type f | xargs stat -f "%m" | md5`

which means find all files in ${targetFolder}, pipe that into stat -f "%m" 1-by-1 and then pipe that into md5. stat -f "%m" [filepath] gives you the last modified timestamp.

Do help me improve it. Thanks!

Related