对流录制脚本的建议改进:超时?

对流录制脚本的建议改进:超时?

我正在尝试调整下面的脚本(取自https://superuser.com/questions/181517/how-to-execute-a-command-whenever-a-file-changes)使我的系统在系统上的特定文件发生更改时记录视频流:

#!/bin/bash

# Set initial time of file
LTIME=`stat -c %Z /path/to/monitored/file`

while true    
do
   ATIME=`stat -c %Z /path/to/monitored/file`

   if [[ "$ATIME" != "$LTIME" ]]
   then    
       echo "RUN COMMAND"
       LTIME=$ATIME
   fi
   sleep 5
done

很明显,该脚本每 5 秒轮询一次受监控文件的时间戳,以查看它是否已更改,如果已更改,则将某些内容回显到终端。同样清楚的是,echo 命令只是一种概念验证,几乎任何其他命令都可以在脚本中取代它。

这是我到目前为止所得到的,几乎可以满足我的目的(recordingscript.sh用于mplayer -dumpstream -dumpfile mystream URL录制 70 分钟的流):

#!/bin/bash

# Set initial time of file
LTIME=`stat -c %Z /path/to/monitored/file`

while true    
do
   ATIME=`stat -c %Z /path/to/monitored/file`

   if [[ "$ATIME" != "$LTIME" ]]; then
      /path/to/my/recordingscript.sh
        break
      LTIME=$ATIME
   fi
   sleep 5
done

剩下的问题是我希望这个脚本在cron每个工作日作为作业运行,例如 5 小时的时间范围内。如果在该时间范围内没有对受监视的文件进行任何更改,我只想让脚本中止/退出,直到下次 cron 启动它为止。如何修改我的改编脚本,使其仅运行大约 5 小时,然后退出?我意识到我可以通过调用脚本来做到这一点,timeout 300m但我认为可能还有其他可能更好的解决方案来做到这一点

答案1

我建议使用以下脚本,其中我做了一些更改:

  • 使用小写变量名
  • 分配一个“放弃”变量,其拼写表达式为“5 小时(秒)”
  • filetomonitor在变量中参数化要监视的文件
  • 根据 bash 变量的行为,将循环更改while true为循环 5 小时,SECONDS该变量计算 shell 启动后的秒数。当 shell 脚本开始时,这从零开始。
  • 将反引号更改为新的$( ... )形式

更新后的脚本:

#!/bin/bash
giveup=$((5 * 60 * 60))
filetomonitor='/tmp/file-to-monitor'

ltime=$(stat -c %Z "$filetomonitor")
while [[ "$SECONDS" -lt "$giveup" ]]
do
  atime=$(stat -c %Z "$filetomonitor")
  if [[ "$atime" -ne "$ltime" ]]
  then
        echo Take action
        break           ## if we're only supposed to act once
        ltime=$atime
  fi
  sleep 5
done

我把 留在那里break,但注释掉了。如果您希望脚本在执行操作后退出(5 小时之前),那么取消注释线break;否则,当前版本的脚本将执行 5 小时(如果 70 分钟的操作从 4:59 开始,则可能会更长),可能会多次调用该操作。

相关内容