1

I am checking for a valid date scrpt.bash test 2019-05-03

date -d $2 2>: 1>:; c=$?

If $c is 1 then the date is invalid. If I enter 2019-05-03 I will get a 0 which is correct. If i enter 2019-05-03u I get a 0 which is incorrect. I can enter 2019-05-03uu then it throws an error. How can I just check if the date is valid.

  • 1
    Is the date always provided in this format? 2019-05-03 – Luciano Andress Martini Mar 12 at 14:24
  • Have you try date -d $2 && c=$? – Romeo Ninov Mar 12 at 14:24
  • Romeo as he says date is returning sucess (0), even if the date contain a additional character at end. So && will make no difference as it will check the command return too to make a decision. – Luciano Andress Martini Mar 12 at 14:25
  • 1
    date is valid against what criteria? Against what your date -d supports? – Stéphane Chazelas Mar 12 at 14:32
2

If date is always provided in this format: '2019-05-03', this will probably work always:

#!/bin/sh -

if [ -n "$2" ] && [ "$(date -d "$2" +%Y-%m-%d 2> /dev/null)" = "$2" ]; then
     echo 'This date is valid'
fi

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.