LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   how to check a valid time argument in Linux? (https://www.linuxquestions.org/questions/linux-newbie-8/how-to-check-a-valid-time-argument-in-linux-4175550684/)

RuijunFan 08-13-2015 09:50 AM

how to check a valid time argument in Linux?
 
Hello
I am writing a bash script xxx, which need to pass an time argument while using .
for example: xxx 4:30 ( 4:30 is 4:30 am )

I need to check in the script if the entered time is valid.
if it is not valid , I will echo " invalid input " something.


anyone could help?
thanks in advance
Ray

HMW 08-13-2015 10:46 AM

A quick one...

Code:

$ echo "4:30" | grep '^[0-9][1-2]\{0,1\}:[0-5][0-9]'
4:30

Code:

#!/bin/bash

# Check if argument is a correct time

if [[ $(echo $1 | grep '^[0-9][1-2]\{0,1\}:[0-5][0-9]') ]]; then
    echo "Correct time"
    exit 0
else
    echo "Invalid time"
    exit 1
fi

On execution:
Code:

$ ./check_time.sh 9:12
Correct time

Code:

$ ./check_time.sh 4:71
Invalid time

Code:

$ ./check_time.sh 12:15
Correct time

This is a very simple regex that can be improved a lot. But since you are apparently dealing with am/pm times, and not a 24 hour clock, it is at least a start.

Best regards,
HMW

RuijunFan 08-13-2015 02:13 PM

Thanks.it is useful

Ray


All times are GMT -5. The time now is 10:23 AM.