Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script compare two date variables [duplicate]

Tags:

I'm trying to compare a date given by a user to a date in a file, basically a text file with lots of dates and times listed.

for example the user would enter a date such as 22/08/2007 and a time of 1:00, what i need the script to do is count how many dates in the text file are after the date given by the user.

I’ve managed to accomplish this by converting each date in the text file to unix timestamp and then comparing the two. Is there no way of simply comparing two dates in bash?

Thanks in advance

like image 880
Xleedos Avatar asked May 05 '11 09:05

Xleedos


People also ask

Can you compare two date strings?

To compare two date strings:Pass the strings to the Date() constructor to create 2 Date objects. Compare the output from calling the getTime() method on the dates.

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

How do you check if two variables are equal in bash?

When comparing strings in Bash you can use the following operators: string1 = string2 and string1 == string2 - The equality operator returns true if the operands are equal. Use the = operator with the test [ command.


1 Answers

The GNU date command can convert a date into the number of seconds since 1970. Try this script:

#! /bin/bash DATE=$(date -d "$3-$2-$1 01" '+%s') COUNT=0 tr '/' ' ' | {     while read D M Y ; do     THIS=$(date -d "$Y-$M-$D 01" '+%s')     if (( THIS > DATE )) ; then         COUNT=$((COUNT + 1))     fi     done     echo $COUNT } 

It expects three arguments and the raw dates in stdin:

for D in $(seq 19 25) ; do echo $D/08/2007 ; done | ./count.sh 22 08 2007 3 

It will work till 2038. ;-)

like image 58
ceving Avatar answered Sep 22 '22 20:09

ceving