【问题标题】:Check if the current time falls within defined time range on UNIX检查当前时间是否在 UNIX 上定义的时间范围内
【发布时间】:2012-11-22 22:34:23
【问题描述】:

考虑以下伪代码

#!/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 脚本的新手,非常感谢您的意见。

【问题讨论】:

  • 这是什么语言或环境?标签上写着ksh,但看起来不像Korn Shell 代码。
  • 稍微扩展一下我的问题,Unix 是一种操作系统(操作系统家族),而不是一种编程语言。您与日期的交互方式将更多地取决于您的编程语言,而不是您的操作系统。 Unix 上的两个标准编程环境是 shell 和 C,但您的示例代码都不是。是的,您将不得不存储开始时间和结束时间,并将它们与您当前的时间进行比较。你如何做到这一点取决于你使用的语言和环境; C 中的结构,shell 中的变量或文件,Java 中的对象,数据库中的列。
  • @BrianCampbell 谢谢!我是 UNIX korn shell 的新手,并编写了我想在 korn shell 中实现的示例伪代码。我自己试了几分钟后会更新问题。

标签: unix solaris ksh scheduler systemtime


【解决方案1】:

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

【讨论】:

  • 感谢@glenn 的详细解释。将确认我的代码并返回..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多