Reputation: 1121
I want to get the number of days since file last modified date to today's date.
I use this $ ls -l uname.txt | awk '{print $6 , "", $7}'
but it gives me the last modified date. I want to know the number of days from a last modified date to today's date.
Any way to do this?
Upvotes: 7
Views: 4465
Reputation: 8924
You could wrap up the differences of GNU and BSD stat with some BASH math and basic readable API:
since_last_modified() {
local modified
local now=$(date +%s)
local period=$2
stat -f %m $1 > /dev/null 2>&1 && modified=$(stat -f %m $1) # BSD stat
stat -c %Y $1 > /dev/null 2>&1 && modified=$(stat -c %Y $1) # GNU stat
case $period in
day|days) period=86400 ;; # 1 day in seconds
hour|hours) period=1440 ;; # 1 hour in seconds
minute|minutes) period=60 ;; # 1 minute in seconds
*) period= ;; # default to seconds
esac
if [[ $period > 0 ]]; then
echo "$(( (now - modified) / period ))"
else
echo "$(( now - modified ))"
fi
}
Basic usage of seconds since last modification:
since_last_modified uname.txt
or minutes saved to a variable
minutes_since=$(since_last_modified uname.txt minutes)
Upvotes: 1
Reputation: 143856
Try creating a script:
#!/bin/bash
ftime=`stat -c %Y uname.txt`
ctime=`date +%s`
diff=$(( (ctime - ftime) / 86400 ))
echo $diff
Upvotes: 2
Reputation: 154846
Instead of using ls
, you can use date -r
to tell you the modification date of the file. In addition to that, date
's %s
specifier, which formats the date in seconds since the epoch, is useful for calculations. Combining the two easily results in the desired number of days:
mod=$(date -r uname.txt +%s)
now=$(date +%s)
days=$(expr \( $now - $mod \) / 86400)
echo $days
Upvotes: 10