Search code examples
bashmacosfswatch

Accepting name of changed file in fswatch with xargs in osx


In osx I am trying to detect when a new file is added to a folder, then execute a script to process that new file. Seems simple, right?

I am doing this:

fswatch  -0  ~/motion-detection | xargs -0 -n1 -I {} ./detectmotion.sh

which will call the shell script detectmotion.sh which consists of:

echo "File added: " $1

for now, at least. I just want to pass the filename of the changed file to detectmotion.sh

I get a blank for $1

Can anyone see what I am doing wrong here?

Thanks in advance!


Solution

  • It is expected to be empty because you are not passing the argument to the script detectmotion.sh which you got from xargs. It should have been

    fswatch  -0  ~/motion-detection | xargs -0 -n1 -I {} ./detectmotion.sh "{}"
    

    Remember that the -I {} flag in xargs represents a place-holder for the value pipe-lined to xargs. So in your attempt as part of the question, you are just storing the value in the place-holder({}) and not actually passing it to the script to make it useful.

    So I modified the command so that you are actually passing the received value to the script which can now be printed when accessed as $1 inside the script.

    Quoting from the man xargs page for -I

    -I replace-str
         Replace  occurrences  of  replace-str  in the initial-arguments with names read from 
         standard input.  Also, unquoted blanks do not terminate input items; instead the 
         separator is the newline character.  Implies -x and -L 1.
    

    In our case the replace-str being used as {}.