I was wondering the best way to implement a counter in bash based on the date. For example if todays date is 5-26-17, a counter will increment every time my bash script is run (starting at 0). So, if the script is run 24 times (once per hour) the counter will be at 24. Now we roll over to the next day 5-27-17, I want to reset the counter to 0 and start incrementing every time the script is run.
My first thought on solving this with a bash script is to run the date utility and create a file based on the current date. After the file is created, using the file to track the counter value. Is there a better way of implementing this?
What I'm trying to do basically is synonymous with using a key value pair. The key is today's date, and the value is the number of times the script has run.
My Solution:
# Create a counter file to keep track of how many times the script
# was run each day.
DATE_COUNTER_FILE=$(date "+%m-%d-%Y").counter
COUNTER=1;
if [ -f $DATE_COUNTER_FILE ]; then
COUNTER=`cat $DATE_COUNTER_FILE`
((COUNTER+=1))
echo $COUNTER > $DATE_COUNTER_FILE
else
touch $DATE_COUNTER_FILE
echo $COUNTER > $DATE_COUNTER_FILE
fi;