Calculate datediff

I'm trying to calculate datediff between string from filename and current date,
i got problem with storing variable from date command

now=$(date  +"%s")
echo "NOW = ${now}";
file=$(ls -1Ap *.txt|grep -v /\$ |tail -1)
echo "file name is $file"
#filename 201710030549.txt

y=$(echo $file|cut -c 1-4)
m=$(echo $file|cut -c 5-6)
d=$(echo $file|cut -c 7-8)

in="$m/${d}/${y}"

$fdate=`$(date -d "$in" +"%s")`
echo "file date = $fdate"
echo $(( (now - fdate) / 86400 )) days

error result

NOW = 1507184947
file name is 201710050619.txt
./test.sh: line 14: 1507136400: command not found
./test.sh: line 14: =: command not found
file date = 
17444 days

This is double command substitution (both ` ... ` and $( ... ) plus the first dollar sign should not be there:

Try:

fdate=$(date -d "$in" +"%s")
1 Like

From your usage of date I would guess that you are (1) using Gnu utilities and therefore (2) are on a Linux distro and therefore (3) using bash.

Try this:

now=$(date  +"%s")
echo "NOW = ${now}";
file=$(ls -1r *.txt|head -1)
echo "file name is $file"
#filename 201710030549.txt

fdate=$(date -d ${filename:0:8} +"%s")
echo "file date = $fdate"
echo $(( (now - fdate) / 86400 )) days

Adding -r to ls allows us to use head instead of tail . Also, it is unlikely that
there will be a directory with the .txt extension the the -p and the grep should not be needed. The -A is also useless in this context.

The variable expansion ${var:offset:len} will produce len characters from the offset position (starting from zero), so ${filename:0:8} will produce 20171003.

date will understand 20171003 as 3rd October 2017 so you don't need to chop up the date.

Hope this helps.

Andrew

1 Like

Thanks, that much cleaner.

ow=$(date  +"%s")
echo "NOW = ${now}";
file=$(ls -1r *.txt|head -1)
echo "file name is $file"
#filename 201710030549.txt
echo ${file:0:8}
fdate=$(date -d ${file:0:8} +"%s")
echo "file date = $fdate"
echo $(( (now - fdate) / 86400 )) days
~
./test2.sh 
NOW = 1507195265
file name is 201710042019.txt
20171004
file date = 1507050000
1 days