Check if time format is valid

How can I validate if time (HH:MM:SS) argument is valid? I got this from web but I can't modify it to exit the script if the time argument is invalid.

echo $1 | awk -F ':' '{ print ($1 <= 23 && $2 <= 59 && $3 <= 59) ? "good" : "bad" }'

ex:
./script.ksh 12:34:21 = okay
./script.ksh 26:67:92 = invalid/exit script

Hello erin00,

Could you please try following and let me know if this helps.

cat script.ksh
echo $1 | awk -F ':' '{match($0,/[0-2][0-4]:[0-5][0-9]:[0-5][0-9]/);A=substr($0,RSTART,RLENGTH);if(A  && $1 !~ /24/){ print "good"}  else {print "bad" }}'

After running script above following will be the output.

./script.ksh 12:34:21
good
./scrpit.ksh 26:67:92
bad
./script.ksh 24:17:12
bad
 

You could use string Invalid in place of bad which I have used above. Also on a Solaris/SunOS system, change awk to /usr/xpg4/bin/awk , /usr/xpg6/bin/awk , or nawk .

Thanks,
R. Singh

This works the same as the code above, but how can I exit the script if the time is invalid

Try this pure shell approach:

B=(${1//:/ })
[ ${B[0]} -le 23 -a ${B[1]} -le 59 -a ${B[2]} -le 59 ] && echo good || echo bad

---------- Post updated at 09:55 ---------- Previous update was at 09:54 ----------

Use exit instead of echo bad .

this ain't working.

`(' is not expected.

Hello erin00,

Could you please try following and let me know if this helps.

cat script.ksh
echo $1 | awk -F ':' '{match($0,/[0-2][0-4]:[0-5][0-9]:[0-5][0-9]/);A=substr($0,RSTART,RLENGTH);if(A && $1 !~ /24/){ print "good";exit 0}  else {print "bad";exit 1;}}'
if [[ $? == 0 ]]
then
     echo "we passed GOOD time test"
else
     exit;
fi

When I run the script with different arguments to check it's functionality it give following output then.

./script.ksh 24:17:12
bad
./script.ksh 23:17:12
good
we passed GOOD time test

Similarly you could change it according to your need like in spite of printing lines which I did after checking $? status, where $? will check the exit status for last command.

Thanks,
R. Singh

1 Like

Well, this is great, but it does'nt allow times like 19:00:00 (because of

[0-2][0-4]

.

Are you sure above will match e.g. 15:10:10?

Yeah, i figured that when i was testing it thoroughly.

That awk statement can be simplified:

echo $1 | awk '/([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]/{print "good";exit 0} {print "bad";exit 1}'

but there is no need to fire up awk for this at all:

#!/bin/ksh
case "$1" in
([01][0-9]:[0-5][0-9]:[0-5][0-9]|2[0-3]:[0-5][0-9]:[0-5][0-9])
	echo okay;;
(*)	echo invalid
	exit 1;;
esac
echo 'Continuing in script after time verification.'
1 Like

Thanks!