我做了一个 bash 函数,它有两个参数。
$1 = start time
$2 = end time
这两个值都是小时格式,因此它们可以从 00
到 23
。
想法是这些函数接受开始和结束时间参数,并在此时间范围内播放一些视频片段。
我首先想到的是:
TIME=$(date +%H)
# # #
#
# Check if its time to play files
# $1 = begin hour, $2 = End hour, $3 = folder with video files
#
# # #
check_if_time_to_play(){
# If current TIME is between begin and end time
if [ $TIME -ge "$1" ] && [ $TIME -lt "$2" ]; then
# Make sure the folder is not empty
if find "$3" -mindepth 1 -print -quit | grep -q .; then
# It's not emty, play the clips
play_files "$3"
else
continue # It's empty! dont play the non-existing clips
fi
else
continue # TIME is not in range, dont play the clips
fi
}
但我很快意识到这是不正确的。
如果我提交,说 $1=22
、$2=05
和 $TIME=23
,剪辑将不会播放。
所以我考虑在最后的 else
语句中添加一个额外的 if
。
像这样:
# check for times where start is bigger than end (ie. 22-05)
if [ "$2" -le "$1" ]; then
#and in here do some range check
fi
所以在这个 if
中,我正在考虑进行一些范围检查,但我不确定该怎么做。
我在想:
if [[ $TIME -eq {$1..24} ] ]&& [ $TIME -eq {00..$2} ]; then
play_files "$3"
fi
所以这个 offcause 不起作用 - 所以我的问题是:
有没有一种方法可以针对一系列数字检查 00
到 23
?
或者,如果您了解我正在尝试做的事情,是否有更好的方法?
如果你不明白,请告诉我 - 我会尝试解释更多。
提前致谢!
最佳答案
尝试以下,它使用bash 的shell arithmetic ,它在多种情况下提供使用熟悉的 C 风格语法的算术计算:
- 以
((...))
或let ...< 的形式作为测试 或没有输出的计算/
- 作为计算,输出结果(算术展开),格式为
$((...))
- 使用整数变量声明和时,用
declare -i
或local -i
声明
- 在 bash 需要数字的其他上下文中,例如数组下标或子字符串索引。
# # #
#
# Check if its time to play files
# $1 = hour now, $2 = begin hour, $3 = End hour, $4 = folder with video files
#
# # #
check_if_time_to_play() {
# Make sure the arguments are interpreted as *decimal* integers
# by evaluating them in an arithmetic context (-i) with prefix '10#',
# indicating number base 10.
# (A leading '0' would cause intepretation as *octal*.)
local -i hourNow=10#$1 startHour=10#$2 endHour=10#$3 play
local dir=$4
# Make sure the folder is not empty.
if ! find "$dir" -mindepth 1 -print -quit | grep -q .; then
return # It's empty! Don't play the non-existing clips.
fi
# Determine if current hour is between begin and end time.
play=0
if (( startHour < endHour )); then
if (( hourNow >= startHour && hourNow < endHour )); then
play=1
fi
else # startHour > endHour: overnight hours
if (( hourNow >= startHour || hourNow < endHour )); then
play=1
fi
fi
if (( play )); then
# Play the clips
play_files "$dir"
else
: # Current hour is not in range, don't play the clips.
fi
}
示例调用:
check_if_time_to_play $(date +%H) 22 05 .
# Hard-coded, to test logic
check_if_time_to_play 23 22 05 .
check_if_time_to_play 11 10 18 .
- 请注意,我已将当前时间作为第一个参数。 (此外,最好避免使用全大写的 shell 变量名称,例如
TIME
,以避免与环境或特殊 shell 变量发生冲突)。 $((...))
输出计算结果,而((...))
解释结果作为测试。- 开始时间 > 结束时间(隔夜)时间范围的情况在单独的
if
分支中处理,其中当前时间必须晚于开始时间或者比(第二天早上)结束时间早或小时。
关于linux - Bash 检查 $var 是否在数字范围内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29232438/