Linux time elapsed bash script

Create the following bash script and put it in a folder with a file called time.txt

You an set the time to sleep. The script will remove all but the last six or seven reports as it runs. When there is a significant time gap (as in the computer slept) when the computer comes back the script will open time.tx and exit.

I used this to see how long my laptop would run before it hibernated. I had to check the time.txt file right away before the last counts were over written.

Open the script in a terminal window to see it running and stop it with ctrl+c after hibernation or whenever.


 

 

#!/bin/bash
# record time until laptop hibernates

#!/bin/bash
# record time until laptop hibernates

start=$(date +”%s”)
seconds=0
sleep2=5
sleep3=$sleep2″s” #s seconds m minutes h hours

echo “Start time was: ” $(date) > ./time.txt
echo “—–” >> ./time.txt
echo  >> ./time.txt
echo  >> ./time.txt

while [ : ]
do
let nowsecs=$(date +”%s”)

sleep $sleep3
clear

nowsecs2=$(date +”%s”)
nowdiff=$(($nowsecs2-$nowsecs))

if [ $nowdiff -gt $sleep2 ]
then
echo  >> ./time.txt
echo xxxx >> ./time.txt
echo “There was a break in the time.” >> ./time.txt
echo “so exiting” >> ./time.txt
xdg-open ./time.txt
exit
fi

echo “started at” $(date)
echo $nowsecs
echo $nowsecs2
echo $nowdiff

seconds=$(($seconds+$sleep2))
let minutes=$seconds/60
let minutes2sec=$minutes*60
let seconds2=$seconds-$minutes2sec

lines=”$(wc -l < ./time.txt)”

echo “number of minutes:” $minutes minutes $seconds2 seconds
# echo “number of lines:” $lines

if [ $lines -gt 24 ]
then
# echo “greater than 24 lines”
sed -i -e 5,10d ./time.txt
fi

echo “check time was:” $(date) >> ./time.txt

echo “time elapsed: ” $minutes minutes $seconds2 seconds >> ./time.txt
echo “–”  >> ./time.txt
echo  >> ./time.txt

done

 

 


end of post