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?
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.
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).
$_ (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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With