Validate date format in a shell script

后端 未结 12 1806
我在风中等你
我在风中等你 2020-11-29 11:11

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 real

12条回答
  •  野性不改
    2020-11-29 12:08

    Though the solution (if [[ $1 =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] && date -d "$1" >/dev/null 2>&1) of @https://stackoverflow.com/users/2873507/vic-seedoubleyew is best one at least for linux, but it gives error as we can not directly compare/match regex in if statement. We should put the regex in a variable and then we should compare/match that variable in if statement. Moreover second part of if condition does not return a boolean value so this part will also cause error.

    So I have done slight modification in the above formula and this modification can also be customized further for various other formats or combination of them.

    DATEVALUE=2019-11-12
    REGEX='^[0-9]{4}-[0-9]{2}-[0-9]{2}$'
    if [[ $DATEVALUE =~ $REGEX ]] ; then
        date -d $DATEVALUE 
      if [ $? -eq 0 ] ; then
        echo "RIGHT DATE"
       else 
        echo "WRONG DATE"
      fi
    else
     echo "WRONG FORMAT"
    fi
    

提交回复
热议问题