mrsorrted
mrsorrted

Reputation: 151

How to check change of contents in file from shell script

I am new to shell scripting, I have requirement to check a date_trigger.txt file continuously for date change.

content of date_trigger.txt are as below :

trigger_date, value
17/03/2021, v1

The script (fetch_date.sh) should wait until date (17/03/2021) inside date_trigger.txt has not changed to current date. date_trigger.txt will be updated by another script with current date, hence the idea/need for fetch_date.sh script is to keep checking date_trigger.txt file and once it has found that date has been updated to current date then exit the code.

I have written a basic shell script for this as below, but so far no luck:

#! /bin/bash

sys_cur_date=$(date +"%d/%m/%Y")
while IFS=, read -r trigger_date value
  do
    while [ $sys_cur_date != $trigger_date ]; do
      echo " Where is my current date ?"
    done
      echo "I got my current date "
      break
  done < date_trigger.txt

Upvotes: 0

Views: 179

Answers (2)

mrsorrted
mrsorrted

Reputation: 151

I got it working, see below code. I think the -n1 in tail command was creating an issue, not sure if that was a typing error or that's an actual syntax.

#! /bin/bash
#fetch system current date
sys_cur_date=$(date +"%d/%m/%Y")

while IFS=, read -r trigger_date value < <(tail -1 date_trigger.txt)
  do
  if [[ $sys_cur_date == $trigger_date ]]; then
    echo "I got my current date"
    break
    #using break statement to control infinte loop here.
  else
    echo $trigger_date
    echo "Where is my current date ?"
  fi
done < date_trigger.txt

Upvotes: 0

Jetchisel
Jetchisel

Reputation: 7791

You could add a sleep inside an infinite while loop, something like this.

#!/usr/bin/env bash

sys_cur_date=$(date +"%d/%m/%Y")

while :; do
  IFS=, read -r trigger_date value < <(tail -n1 date_trigger.txt)
  if [[ $sys_cur_date != "$trigger_date" ]]; then
    printf "Where is my current date %s\n" "$trigger_date"
  else
    printf "I got my current date %s\n" "$trigger_date"
    break
  fi
  sleep 1
done

Since you're only interested at the second line which contains the date, the tail -n1 only prints the last line for read to process.

If you're not going to process value later, it can be replaced with an underscore _. It is like a dummy variable, just saying.

Upvotes: 1

Related Questions