Doing date calculations in bash shell arrays and looping and stuff
I was working with a set of files, and some of them had unix epoch time entries for start and stop time. I wanted to calculate the number of days between start and stop. I cobble together the following code chunk that provides the facility for just that.
FILES=( `find run -type f -name "D*" -mtime -20 -print`)
#obtain the files used in the run
counter=0
while [ ${FILES[$counter]} ]; do
STARTTIME[$counter]=`grep -P 'S:\d{3,}' ${FILES[$counter]} | cut -f 2 -d ":" `
#throw start time into its own array
ENDTIME[$counter]=`grep -P 'T:\d{3,}.*Done' ${FILES[$counter]} | cut -f 2 -d ":" `
#throw end time into its own array
if [ ! ${STARTTIME[$counter]} ]; then
echo "ERROR: Variable STARTTIME not defined in file: ${FILES[$counter]}"
elif [ ${ENDTIME[$counter]} ]; then
TOTALTIME[$counter]=`echo "scale=2;( ${ENDTIME[$counter]} - ${STARTTIME[$counter]} ) / 86400"| bc `
#since both start and stop time exist calculate using "bc" to 2 decimal places.
#Note the use of scale=2 in the echo.
#This was determined to be the shortest way to implement the calculation.
else
echo "ERROR: Variable ENDTIME not defined in file: ${FILES[$counter]}"
fi
let counter=$counter+1
done
0 Comments:
Post a Comment
<< Home