mtk*_*mtk 12 shell bash shell-script date time
我需要检查当前时间并中止脚本,如果它不是我应该运行的正确时间。此外,如果其他人运行它,它应该中止。
例如:我需要我的脚本仅在晚上 10 点到凌晨 2 点(4 小时窗口)之间启动时运行。
目前我正在做以下事情。花时间date +%k%M
与硬编码数字进行比较
#!/bin/sh
currTime=`date +%k%M`
check_time_to_run()
{
tempTime=$1
if [ $tempTime -gt 200 -a $tempTime -lt 2200 ]; then
echo "Time is between 2 AM and 10 PM. Aborting."
exit 1
else
echo "Time is after 10 PM and before 2 AM. Running normally."
fi
}
check_time_to_run $currentTime
Run Code Online (Sandbox Code Playgroud)
我想知道是否还有其他有效的方法来进行时间比较sh
或bash
?
这对我来说看起来很完美。是什么让您认为它应该改进?
无论如何,改进它的方法可能是:
zsh
或ksh93
gawk
(比 bash 小,但不比 dash 但可以避免额外的叉子):例子:
#! /usr/bin/gawk -f
BEGIN {now = strftime("%k%M")+0; exit(now > 200 && now < 2200)}
Run Code Online (Sandbox Code Playgroud)