gpt4 book ai didi

linux - 需要在 bash 中的两个给定时间之间生成时间值

转载 作者:太空宇宙 更新时间:2023-11-04 12:12:39 26 4
gpt4 key购买 nike

所以我是 bash 的新手,我必须制作一个脚本,其中包含动态回显行和不断变化的时间戳 HH:MM。所以当我说

sh run.sh 03:40 05:40

它应该在给定范围内回显所有时间例如:03:31 03:32 ....... 05:39 05:40

我知道循环很简单,但我想不通。有什么帮助吗?

我有一段不太好的代码,现在还不能用。

echo "Enter from Hour:"
read fromhr
echo "Enter from Min:"
read frommin
echo "Enter to Hour:"
read tohr
echo "Enter to Min:"
read tomin
while [ $fromhr -le $tohr ]; do
while [ $frommin -le $tomin ]; do
echo "$fromhr:$frommin"
if [ $frommin -eq 60 ]; then
frommin=0
break
fi
((frommin++))
done
if [ $fromhr -eq 24 ]; then
fromhr=0
fi
((fromhr++))
done

最佳答案

示例 1:仅使用 bash,速度更快:

#!/bin/bash
# - input data
fh=03 # from hour
th=05 # to hour
fm=30 # from minute
tm=30 # to minute

for ((h=fh;h<=th;h++)); do
for ((m=0;m<=59;m++)); do
[[ $h -le $fh && $m -lt $fm ]] && continue
[[ $h -ge $th && $m -gt $tm ]] && break
printf '%02d:%02d\n' $h $m
done
done

示例2:使用date来回转换,代码更短,但速度更慢:

#!/bin/bash
# 1) input data
ft='03:30' # from time
tt='05:30' # to time
# 2) convert to Epochtime (second)
f=`date +%s -d "$ft"` # from
t=`date +%s -d "$tt"` # to

for ((s=f;s<=t;s+=60)); do # 60 seconds = 1 minute
date +%H:%M -d @$s # convert from Epochtime to H:M
done

关于linux - 需要在 bash 中的两个给定时间之间生成时间值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48403997/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com