Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script, watch folder, execute command

Tags:

bash

shell

macos

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 
like image 562
ThomasReggi Avatar asked Jun 25 '11 01:06

ThomasReggi


People also ask

How do I monitor a folder in Linux?

In Linux, we can use the inotify interface to monitor a directory or a file. We do this by adding a watch to the directory or file. When we add a watch to a file, we can monitor it. For example, we'll know when a process opens, modifies, reads closes, moves, or deletes the file.

How do I view a folder in Bash?

Basic Bash Commandscd path-to-directory : The command followed by a path allows you to change into a specified directory (such as a directory named documents ). cd .. (two dots). The .. means “the parent directory” of your current directory, so you can use cd .. to go back (or up) one directory.

How do I run a path in a Bash script?

In order to run a Bash script from anywhere on your system, you need to add your script to your PATH environment variable. Now that the path to the script is added to PATH, you can call it from where you want on your system. $ script This is the output from script!


1 Answers

To continuously recursively monitor folder (md5) and execute a command on change:

daemon() {     chsum1=""      while [[ true ]]     do         chsum2=`find src/ -type f -exec md5 {} \;`         if [[ $chsum1 != $chsum2 ]] ; then                        if [ -n "$chsum1" ]; then                 compile             fi             chsum1=$chsum2         fi         sleep 2     done } 

Works on my OS X as I do not have digest.

On Linux, you can use md5sum as a replacement for the md5 command.

like image 67
Radek Avatar answered Oct 05 '22 01:10

Radek