Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate date format in a shell script

I have to create a Shell Script wherein one of the parameters will be the date in the format dd/mm/yyyy. My question is, how can I check if the Date passed as parameter really follows this Date Format? I tried to use the grep command as below:

if echo "$1" | grep -q '^[0-3][0-9]/[0-1][0-9]/[0-9]\{4\}$'

but it didn't give the correct format because the day for example can be 33, 34, (...), that is not really the correct format. Anyone know something that can really check if the date passed really follows the format dd/mm/yyyy ?

like image 892
Jairo Franchi Avatar asked Sep 11 '13 01:09

Jairo Franchi


People also ask

How to check date format in shell script?

Sample shell script to display the current date and time #!/bin/bash now="$(date)" printf "Current date and time %s\n" "$now" now="$(date +'%d/%m/%Y')" printf "Current date in dd/mm/yyyy format %s\n" "$now" echo "Starting backup at $now, please wait..." # command to backup scripts goes here # ...

What is date in shell script?

Task: Display date in mm-dd-yy format Open a terminal and type the following date command: $ date +"%m-%d-%y" Sample outputs: 02-27-07.

Which command is used for displaying date in the format dd mm yyyy in Unix?

Linux date Command Format Options These are the most common formatting characters for the date command: %D – Display date as mm/dd/yy. %Y – Year (e.g., 2020) %m – Month (01-12)

How do I print Yyyymmdd format in Unix?

Using date command – To print the results in YYYY-MM-DD format, you can use %Y-%m-%d or %F options with date command. Here the %F option is an alias for %Y-%m-%d. Using printf command – Rather than using the date command, the print command also provides a built-in date formatted in bash (>=4.2).


1 Answers

Use date

date "+%d/%m/%Y" -d "09/99/2013" > /dev/null  2>&1
 is_valid=$?

The date string must be in "MM/DD/YYYY" format.

If you do not get 0 then date is in invalid format.

like image 138
P̲̳x͓L̳ Avatar answered Oct 15 '22 09:10

P̲̳x͓L̳