Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

bash date validate 1

Status
Not open for further replies.

vodkadrinker

Technical User
May 16, 2002
163
0
0
GB
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...
 
Found a quick way round this.

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

Just to check the format in Bash 3.0 or newer I would prefer :
Bash:
[teal][[[/teal] [green][i]"$date"[/i][/green] [teal]=~[/teal] [teal]^[[:[/teal]digit[teal]:]][/teal]{[purple]4[/purple]}[teal]([/teal]-[teal][[:[/teal]digit[teal]:]][/teal]{[purple]2[/purple]}[teal])[/teal]{[purple]2[/purple]}$ [teal]]][/teal]

But personally I would allow dates in any format understood by GNU [tt]date[/tt]. ( Systems with Bash usually have such [tt]date[/tt] 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:
[navy]date[/navy][teal]=[/teal][green][i]"$( date -d '2013-03-07' +'%F' 2> /dev/null )"[/i][/green]
[teal][[[/teal] [green][i]"$date"[/i][/green] [teal]]][/teal] [teal]||[/teal] echo [green][i]'error : missing, invalid or incorrectly formatted date'[/i][/green]


Feherke.
[link feherke.github.com/][/url]
 
Thanks feherke good to know the format option as well, handy for pattern matching things other than dates too.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top