Jewenile
Jewenile

Reputation: 315

bash: perform action (grep) when file changed

Googled a lot and didnt, susprisingly, find a working solution. Im an engineer, not a programmer. Just need this tool.

So: I have a file "test2.dat" that I want to grep every time it changes.

I dont have inotifywait or when-changed or any similar stuff installed and I dont have the rights to do so (and dont even want to as I would like this script to be working universally).

Any suggestions?

What I tried:
LTIME='stat -c %Z test2.dat'

while true    
do
   ATIME='stat -c %Z test2.dat'

   if [[ "$ATIME" != "$LTIME" ]]
   then    
       grep -i "15 RT" test2.dat > test_grep2.txt
       LTIME=$ATIME
   fi
   sleep 5
done

but that doesn't do basically anything.

Upvotes: 2

Views: 357

Answers (1)

Inian
Inian

Reputation: 85780

Your syntax for command-substitution is wrong. If you are expecting the command to run within the quotes you are wrong. The command-substitution syntax in bash is to do $(cmd)

Also by doing [[ "$ATIME" != "$LTIME" ]] you are doing a literal string comparison which will never work. Once you store LTIME=$ATIME the subsequent comparison of the strings will never be right.

The appropriate syntax for your script should have been,

#!/bin/bash

LTIME=$(stat -c %Z test2.dat)

while true    
do
   ATIME=$(stat -c %Z test2.dat)    
   if [[ "$ATIME" != "$LTIME" ]]
   then    
       grep -i "15 RT" test2.dat > test_grep2.txt
       LTIME="$ATIME"
   fi
   sleep 5
done

I would recommend using lower-case letters for variable definitions in bash, just re-used your template in the example above.

Upvotes: 1

Related Questions