Tuesday, November 16, 2021

[SOLVED] How to execute a shell script when a file changes?

Issue

In my directory, I have a text file called test.txt and I have a shell script called targetscript.sh.

I want to run this shell script when any changes occur on test.file. On my server, I have no option to install new tools like inotfy or similar like anything.

So after some research I wrote the following shell script which will take the time stamp of test.txt and if any changes occur it will trigger the targetscript.sh.

#!/bin/bash
while true
do
    ATIME=$(stat -c %Z /home/haider/test.txt)
    if [[ "$ATIME" != "$LTIME" ]]; then
        echo "RUN COMMNAD"
        ./targetscript.sh
        LTIME=$ATIME
    fi
    sleep 5
done

But I am getting the following error. enter image description here


Solution

First of all, the [[1617030570: command not found error is caused by a missing space after the [[ (Not shown in question)

Secondly, you'll always run ./targetscript.sh on the first iteration since LTIME isn't set. Therefore the "$ATIME" != "$LTIME" will fail, and the sh script will be executed.

Consider setting $LTIME before the while-loop:

#!/bin/bash
LTIME=$(stat -c %Z /private/tmp/jq/tst.txt)
while true
do
  ATIME=$(stat -c %Z /private/tmp/jq/tst.txt)
  if [[ "$ATIME" != "$LTIME" ]]; then
        echo "RUN COMMNAD"
        ./targetscript.sh
        LTIME=$ATIME
  fi
  sleep 2
done


Answered By - 0stone0