Bash: How can I subtract two lines of time using bash?

I found the following script to find the age of the lock file:

#!/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:

  • Exiting ls -ltrh aggregator.lock |awk -F" " '{print $7}' gives me time in HH: MM format, not HH: MM: SS and exiting date +"%T"gives me time in HH: MM: SS format (as needed), so how can I get the file modification time in seconds?
  • I don’t know how to subtract between times ... I wanted to do something like $now - $locktimeto get the delta of seconds between both variables, how can this be done?

EDIT: The value of the script is to find how long the lock file has existed ... There it is a 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

... - , script, , , m , .

+4
5

, ,

stat -c %Y file 

date +%s 

. $(( ... )) . , Unix , //.

, ., , fooobar.com/questions/208925/...

, :

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 )) 

echo printf,

printf '%02dd:%02dh:%02dm:%02ds\n' $days $hours $mins $secs

00d:18h:42m:27s

, %02d - . , - .

, script/program, bash time /usr/bin/time ( ), script, :

was=$(date +%s)
...run your script...
now=$(date +%s) 

, .

+5

stat ( GNU coreutils, GNU/linux), :

stat -c%Y aggregator.lock

man stat , , (-c).

, :

elapsed=$(( $(date +%s) - $(stat -c%Y aggregator.lock) ))

($(( ... )) - bash -syntax , . man bash)

+4

, Unix ( , 1 1970 ). GNU date, .

now=$(date +%s)
locktime=$(date +%s --date 13:50:32)
diff=$(( now - lock time ))

, , stat, , .

+2

find , - :

locktime=$(find -maxdepth 1 -name aggregator.lock -printf '%T@')
now=$(date +%s)
delta=$(($now - $locktime))
printf "The file was modified %.0f seconds ago" $delta
0

script, :

#!/bin/bash
#file="/home/build/aggregator/scripts/aggregator.lock"
file="$1"

if [ -e "$file" ]; then 
    now=$(date +%s)                          
    was=$(stat -c%Y $file) 
    elapsed=$((now - was))
    echo $elapsed 
else
    echo 0
fi

Zabbix script , , "0", :

[root@zabbix ~]# zabbix_get -s 10.200.X.X -k check.lock[/home/build/aggregator/scripts/aggregator.lock]
14
[root@zabbix ~]#

.

0

Source: https://habr.com/ru/post/1540720/


All Articles