d0pchu
d0pchu

Reputation: 11

date & counter bash script

I need Bash script to generate automatic tags in file.tag. When the script is called several times during the same day, the COUNTER must be increased.The COUNTER must be reset back to 001 when the date has changed.Thanks

I have tried

#!/bin/bash 
touch file.tag 
counter=0 
date=$(date +"%y.%m.%d") 
echo $date.$counter > file.tag

Upvotes: 0

Views: 299

Answers (2)

Jay jargot
Jay jargot

Reputation: 2868

I noticed in your example that file.tag always has only one line: the last tag, right?

Give this version a try (tested and checked with shellcheck):

#!/bin/bash 

touch file.tag 
date=$(date +"%y.%m.%d") 
counter=0
if [ -s file.tag ]
then
  lastline=$(tail -1 file.tag)
  if [ "${date}" = "$(expr "${lastline}" : "^\([0-9.][0-9.]*\)[.][0-9][0-9]*$")" ]
  then
    counter=$(expr "${lastline}" : "^[0-9.][0-9.]*[.]\([0-9][0-9]*\)$")
    counter=$((counter + 1))
  fi
fi
printf "%s\n" "${date}.${counter}" > file.tag

The script checks if the file.tag is not empty.

If not empty, it extracts the last date from the file.tag and compare it to the current date.

If the dates are equal, then it extracts the last value of the counter from the file.tag and increment it

finaly it updates the file.tag with the new tag

Upvotes: 0

SLePort
SLePort

Reputation: 15461

Try this :

[[ ! -f ./file.tag ]] && touch file.tag

declare -i counter
dt=$(date +'%y.%m.%d')
counter=$(grep -c "${dt}" file.tag)
(( counter++ ))

printf '%s.%03d\n' ${dt} ${counter} >> file.tag

This script :

  • counts the number of occurences of current date in file.tag
  • increments this counter
  • adds date and counter to file.tag

If date if not matched, grep -c will return 0, starting another day with 001

Upvotes: 1

Related Questions