【问题标题】:How to retrieve the current minute and check if that minute is in a file如何检索当前分钟并检查该分钟是否在文件中
【发布时间】:2016-04-06 18:56:46
【问题描述】:

我有一个每分钟运行的脚本,我想检查当前分钟是否包含在从文本文件分配的变量中。

clip_time=(

clip_time.cfg 是一个文本文件,如下所示: 00,05,10,15,20,25,30,35,40,45,50,55

在 if 语句中: 如果“date '+%M'”的当前分钟在变量中,则说“45” 这样做,如果没有,就这样做

如果分钟是 45,而不是 46、47、48、49,它将触发。但在 50 时触发。

也就是说,每分钟运行一次脚本,如果分钟在变量中,则执行此操作,如果没有休眠 30 秒并继续。

变量不一定是每 5 分钟一次。可能是 05、08、11、22、35。

【问题讨论】:

    标签: linux bash date time


    【解决方案1】:

    一种方法是检查 clip_time 字符串是否包含当前分钟作为子字符串:

    clip_time="$(cat /home/project/data/clip_time.cfg)"
    minute="$(date +%M)"
    
    # The 2 asterisks make this a glob match, which should find that
    # minute in the list, if it's in there
    if [[ "$clip_time" == *"$minute"* ]]; then
        echo "$minute is in the list"
    else
        echo "$minute is NOT in the list"
    fi
    

    【讨论】:

      【解决方案2】:

      要将当前分钟存储在变量中,请执行此操作

      minute=$(date +"%M");
      

      然后搜索,可以使用grep

      echo $(grep $minute file.txt);
      

      这里是 grep 的手册页

      http://www.gnu.org/software/grep/manual/grep.html

      【讨论】:

        【解决方案3】:

        你可以像这样一起使用 grep 和 date:

        grep "\b`date "+%M"`\b" test
        

        带有单词边界,甚至可以添加 -q 标志以返回 0 或 1,如下所示:

        grep -q "\b`date "+%M"`\b" test
        

        【讨论】:

          猜你喜欢
          • 2014-05-11
          • 1970-01-01
          • 1970-01-01
          • 2016-02-22
          • 1970-01-01
          • 1970-01-01
          • 2014-08-30
          • 2021-06-06
          • 2011-12-03
          相关资源
          最近更新 更多