unix - 检查当前时间是否在 UNIX 上定义的时间范围内

标签 unix solaris ksh scheduler systemtime

考虑下面的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
}

是否有更好的方法来实现 checkIfWithinRange()? UNIX 中是否有任何内置函数可以更轻松地执行上述操作?我是 korn 脚本编写的新手,非常感谢您的意见。

最佳答案

return 命令用于返回退出状态,而不是任意字符串。这与许多其他语言不同。您使用 stdout 传递数据:

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
}

此外,您需要更多语法来调用该函数。当前您正在比较 if 条件中的文字字符串 "getCurrentMinute"

if [[ $(getCurrentMinute) -ge $rangeStartTime_min && ...

如果有点不同的话我会做

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

关于unix - 检查当前时间是否在 UNIX 上定义的时间范围内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13717501/

相关文章:

regex - 从 Unix 中的一行中提取字符串

shell - 将 stderr 和 stdout 复制到文件以及 ksh 中的屏幕

c - 如何为接受命令行参数的程序创建 Makefile

unix - 在 bash_profile 中设置路径

shell - 查找包含字符串出现次数的文件

solaris - 如何编写 dtrace 脚本来转储 Solaris 10 上崩溃进程的堆栈?

linux - Solaris 10 - 用数字后缀拆分

c - 用 C 打开 LDAP 客户端 - 如何替换已弃用的 API

algorithm - KornShell 从具有 n 个对象的集合中生成 k 个对象的组合数

bash - 如何编写一个可以切换到 bash 的 shell?