Consider the below PSUEDO-CODE:
#!/bin/ksh
rangeStartTime_hr=13
rangeStartTime_min=56
rangeEndTime_hr=15
rangeEndTime_min=05
getCurrentMinute() {
return `date +%M | sed -e 's/0*//'`;
# Used sed to remove the padded 0 on the left. On successfully find&replacing
# the first match it returns the resultant string.
# date command does not provide minutes in long integer format, on Solaris.
}
getCurrentHour() {
return `date +%l`; # %l hour ( 1..12)
}
checkIfWithinRange() {
if [[ getCurrentHour -ge $rangeStartTime_hr &&
getCurrentMinute -ge $rangeStartTime_min ]]; then
# Ahead of start time.
if [[ getCurrentHour -le $rangeEndTime_hr &&
getCurrentMinute -le $rangeEndTime_min]]; then
# Within the time range.
return 0;
else
return 1;
fi
else
return 1;
fi
}
Is there a better way of implementing checkIfWithinRange()
? Are there any inbuilt functions in UNIX that make it easier to do the above? I am new to korn scripting and would appreciate your inputs.
The return
command is used to return an exit status, not an arbitrary string. This is unlike many other languages. You use stdout
to pass data:
getCurrentMinute() {
date +%M | sed -e 's/^0//'
# make sure sed only removes zero from the beginning of the line
# in the case of "00" don't be too greedy so only remove one 0
}
Also, you need more syntax to invoke the function. Currently you are comparing the literal string "getCurrentMinute"
in the if condition
if [[ $(getCurrentMinute) -ge $rangeStartTime_min && ...
I would do if a bit differently
start=13:56
end=15:05
checkIfWithinRange() {
current=$(date +%H:%M) # Get's the current time in the format 05:18
[[ ($start = $current || $start < $current) && ($current = $end || $current < $end) ]]
}
if checkIfWithinRange; then
do something
fi