Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if argument is a valid date in bash shell

Tags:

linux

bash

shell

I am writing a bash shell script in Linux, this program will accept a date (mm-dd-yyyy) as a parameter. I am wondering if there is a simply way to check if the date is valid? is there an operator and I can just use test to check?

like image 476
Gary Avatar asked May 25 '12 17:05

Gary


People also ask

How do you check if a date is valid in Unix?

There are multiple ways you can validate date format in shell script. You can compare date format with regular expression or you can use inbuilt date command to check given date format is valid or not. I am sharing a simple date command to validate the date in YYYY-mm-dd format.

What does $() mean in bash?

Again, $() is a command substitution which means that it “reassigns the output of a command or even multiple commands; it literally plugs the command output into another context” (Source).

What is $_ in bash?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.


1 Answers

You can check with date -d "datestring"

So date -d "12/31/2012" is valid, but using hyphens, e.g. date -d "12-31-2012", is not valid for date.

You can also use words: date -d 'yesterday' or date -d '1 week ago' are both valid.

like image 124
johnshen64 Avatar answered Oct 13 '22 05:10

johnshen64