3

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.

4
  • 1
    Is the date always provided in this format? 2019-05-03 Commented Mar 12, 2019 at 14:24
  • Have you try date -d $2 && c=$? Commented Mar 12, 2019 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. Commented Mar 12, 2019 at 14:25
  • 1
    date is valid against what criteria? Against what your date -d supports? Commented Mar 12, 2019 at 14:32

1 Answer 1

4

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
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .