I've crated the next script in order to find a lock file's age:
#!/bin/bash
now=`date +"%T"`
lock="aggregator.lock"
find . -name $lock -type f
if [ $? != 0 ];
then
exit
else
ls -ltrh $lock 2&>/dev/null
fi
if [ $? != 0 ];
then
locktime=`ls -ltrh aggregator.lock |awk -F" " '{print $7}'`
else
echo "File not found"
fi
I have two problems:
ls -ltrh aggregator.lock |awk -F" " '{print $7}'
gives me the time in format HH:MM rather than HH:MM:SS and the output
of date +"%T"
gives me the time in format HH:MM:SS (As needed), so
how can I get the modify time of the file with seconds?$now - $locktime
in order to get the seconds delta between both variables, how can it be done?EDIT: The meaning of the script is to find how long the lock file existed... There's this script:
device0="/home/build/aggregator/scripts/aggregator.lock"
if [ -e "$device0" ]
then
echo process is allready running
else
touch $device0
java -Xms6g -Xmx6g -jar /home/build/aggregator/aggregator-1.0-SNAPSHOT-jar-with-dependencies.jar
rm $device0
fi
Which creates the lock file... the only purpose of the creation of the lock file is to give me an indication about how long was the script's run time, just thought this information is needed as well, because I'm not looking for how much time passed since the last modification of the file.
Thanks in advance
To find out how much time ago a file was last modified, you can use
stat -c %Y file
To have the last modification date of the time in seconds since the epoch, and
date +%s
for the current date in the same units. Then simply subtracting them with $(( ... ))
will give you the elapsed seconds since the last modification of file. Notice that Unix file system normally do not store the creation date, just the last access/change/modification date.
To convert back to a human-readable format, see for example https://stackoverflow.com/a/12199798/2907484
So basically:
now=$(date +%s)
was=$(stat -c%Y file)
elapsed=$((now - was))
days=$((elapsed/86400))
hours=$(( (elapsed-days*86400)/3600 ))
mins=$(( (elapsed-days*86400 - hours*3600)/60 ))
secs=$(( elapsed - days*86400 - hours*3600 - mins*60 ))
and now you can format the output with echo
or printf
as you like
printf '%02dd:%02dh:%02dm:%02ds\n' $days $hours $mins $secs
will output
00d:18h:42m:27s
Probably the format %02d
is not so appropriate for days --- but you got the idea. You can add weeks, years or whatever easily too.
To see how much time a script/program use to run, you can use the bash builtin command time
or the utility /usr/bin/time
(be sure to not confound them), or you can follow the idea in this script by using:
was=$(date +%s)
...run your script...
now=$(date +%s)
and continue as above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With