INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

bash date validate

bash date validate

(OP)
I am writing a simple script in bash so that it is easily portable, is there an easy way to validate a string is a date?

Example

My string should come back in the format "2013-03-07" CCYY-MM-DD however it may be blank or anything, if it's not in a date format then I would like to ignore it.

CODE -->

if [ $mydatestring == validdate ] ; then
    ...do some stuff... 

RE: bash date validate

(OP)
Found a quick way round this.

CODE -->

if (date --date $mydatestring > /dev/null 2>&1); then 

RE: bash date validate

Hi

Just to check the format in Bash 3.0 or newer I would prefer :

CODE --> Bash

[[ "$date" =~ ^[[:digit:]]{4}(-[[:digit:]]{2}){2}$ ]] 

But personally I would allow dates in any format understood by GNU date. ( Systems with Bash usually have such date implementation. ) The following will transform many valid date formats to CCYY-MM-DD and reduces the unknown formats and invalid dates to empty string :

CODE

date="$( date -d '2013-03-07' +'%F' 2> /dev/null )"
[[ "$date" ]] || echo 'error : missing, invalid or incorrectly formatted date' 

Feherke.
http://feherke.github.com/

RE: bash date validate

(OP)
Thanks feherke good to know the format option as well, handy for pattern matching things other than dates too.

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close