Monday, May 13, 2013

DATE with BASH Shell

Was struggling to get date validated in linux ... writing a script with all that date parsing checks (valid day, month etc.) naah there mus be some easy way, something that is built in. The OS itself manages date and time so it should have the logic built in. Why not leverage it.

Came across this date command in shell, which is designed to handle relative date calculations and return/print them to you in a user defined way.

Everyone is familiar with the $ date command

cmd:   $ date
result:  Tue May 14 07:47:45 IST 2013 


Now getting the previous day
cmd:   $ date --date="yesterday"
result:  Tue May 13 07:50:35 IST 2013 



Now getting the next day
cmd:   $ date --date="next day"
result:  Tue May 15 07:50:55 IST 2013 

Looks  great isn't it and not only this one can use different string formats to get the same output
Example

cmd:   $ date --date="1 days ago"   or
cmd:   $ date --date="1 day ago"  or
cmd:   $ date --date="-1 day"    or
cmd:   $ date --date="yesterday"    
result:  Tue May 13 07:50:35 IST 2013



Example of various string formats is
Past:
cmd:   $ date --date="yesterday"
cmd:   $ date --date="20 minute ago"
cmd:   $ date --date="2 hour ago"
cmd:   $ date --date="last Friday"
cmd:   $ date --date="10 days ago"
cmd:   $ date --date="10 week ago"
cmd:   $ date --date="10 month ago"

Future:
cmd:   $ date --date="tommorrow"
cmd:   $ date --date="20 minute"
cmd:   $ date --date="2 hour"
cmd:   $ date --date="this Friday"
cmd:   $ date --date="10 days "
cmd:   $ date --date="10 week"
cmd:   $ date --date="10 month "


Its amazing... very nicely coded and not only this you can specify your custom date format

cmd:   $ date --date="tommorrow" + "%d/%m/%Y"

Hope you find it interesting and helpful too..

Have a nice time playing with your dates. -S