[英]Shell script to run through the day to create files at particular time
我希望创建一个Shell脚本,该脚本将在一天中的特定时间创建文件。
示例案例。 一旦执行了Shell脚本,就应该在一天的特定时间在/ tmp / work /目录中创建文件。
当时间为01:00 Hrs时,应创建abc.txt 。
当时间为06:00 Hrs时 ,应创建def.txt 。
时间为13:00 Hrs时 ,应创建hij.txt 。
当时间为23:00 Hrs时 ,应创建xyz.txt 。
所有文件都应具有“ THIS IS TEST FILE。 ”这样的内容,以使文件大小大于0个字节。
在那个时间点可以执行以下操作吗?
echo "THIS IS TEST FILE." > /tmp/work/abc.txt ## at 01:00 Hrs
echo "THIS IS TEST FILE." > /tmp/work/def.txt ## at 06:00 Hrs
等等...
在大多数情况下,您应该使用诸如at
或cron
类的调度工具,如先前的答案中所述,如如何在特定时间在Linux上运行脚本? ; 但是,如果您确实需要长时间运行的脚本,则以下内容将一直运行到一天结束,并轮询时间。
因为它使用printf %(...)T -1
而不是date
命令来检查时间,所以此轮询的开销很小(但需要bash 4.2或更高版本)。 通过将sleep 1
更改为sleep 60
来降低轮询速率将导致更有效但更慢的周期。 请注意,不能保证sleep
能够等待所请求的确切时间(特别是在负载较重的系统上, sleep 60
可以比请求的60秒更长的睡眠时间),因此检查错过的轮询时间很重要!
#!/usr/bin/env bash
case $BASH_VERSION in ''|[123].*|4.[01].*) echo "ERROR: Bash 4.2 or newer required" >&2; exit 1;; esac
declare -A timestops=(
[01:00]="abc.txt"
[06:00]="def.txt"
[13:00]="hij.txt"
[23:00]="xyz.txt"
)
printf -v run_on_date '%(%Y-%m-%d)T' -1
printf -v last_time '%(%H:%M)T' -1
while sleep 1; do
printf -v curr_time '%(%H:%M)T' -1
printf -v curr_date '%(%Y-%m-%d)T' -1
[[ "$curr_time" = "$last_time" ]] && continue
[[ "$curr_date" = "$run_on_date" ]] || { echo "Day ${run_on_date} has ended; exiting" >&2; exit 0; }
for evt_ts in "${!timestops[@]}"; do
if [[ $curr_time = "$evt_ts" ]] || [[ $curr_time > $evt_ts && $last_time < $evt_ts ]]; then
evt_file=${timestops[$evt_ts]}
echo "THIS IS TEST FILE." >"/tmp/work/$evt_file"
fi
done
last_time=$curr_time
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.