Check date and time entered by user on UNIX

I have a shell script that uses the date and time parameters entered by the user. Date as mm / dd / yyyy and Time as HH: MM. What would be the easiest way to verify that the user entered the correct date [month should be less than 12 .... for MM time should be less than 60 ... Do we have any built-in functions on UNIX to check the timestamp?

+4
source share
3 answers

You can use the unix date tool to parse and validate it for you and verify the return code, for example.

Valid date, return code 0:

joel@bohr :~$ date -d "12/12/2000 13:00" Tue Dec 12 13:00:00 GMT 2000 joel@bohr :~$ echo $? 0 

Invalid date, return code 1:

 joel@bohr :~$ date -d "13/12/2000 13:00" date: invalid date `13/12/2000 13:00' joel@bohr :~$ echo $? 1 

You can change the input format accepted by date using the + FORMAT parameter ( man date )

Putting it all together as a little script:

 usrdate=$1 date -d "$usrdate" > /dev/null 2>&1 if [ $? -eq 0 ]; then echo "Date $usrdate was valid" else echo "Date $usrdate was invalid" fi 
+2
source

You can use grep to make sure the input matches the correct format:

 if ! echo "$INPUT" | grep -q 'PATTERN'; then # handle input error fi 

where PATTERN is a regular expression that matches all valid inputs and only valid inputs. I leave you this diagram, -).

0
source

(Late answer)

Something you can use:

 ... DATETIME=$1 #validate datetime.. tmp=`date -d "$DATETIME" 2>&1` ; #return is: "date: invalid date `something'" if [ "${tmp:6:7}" == "invalid" ]; then echo "Invalid datetime: $DATETIME" ; else ... valid datetime, do something with it ... fi 
0
source

Source: https://habr.com/ru/post/1334495/


All Articles