所以我是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
答案 0 :(得分:0)
请注意,如果您将其比较小于,则不太可能达到小时/日期更改。比如,从20:00到05:00迭代甚至不会发生;如果你从12:38迭代到17:12,则不会有任何分钟改变(内循环的条件立即为假)。建议的步骤很少。
将每个条件的运算符更改为frommin++
- le'。
在相应的溢出检查之前移动两个增量(fromhr++
和# an Article record
polymorphic_url(record) # same as article_url(record)
# a Comment record
polymorphic_url(record) # same as comment_url(record)
# it recognizes new records and maps to the collection
record = Comment.new
polymorphic_url(record) # same as comments_url()
# the class of a record will also map to the collection
polymorphic_url(Comment) # same as comments_url()
)(否则您将在输出中经常看到24小时60分钟)。
试试这个,看看你是否想要美化它。
答案 1 :(得分:0)
示例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=1;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
答案 2 :(得分:0)
示例代码:
#!/bin/bash
# Convert the given start/end time to seconds
# Replace time string with required HH:MM value
start_t=`date -d "03:30" +%s`
end_t=`date -d "03:33" +%s`
while [ ${start_t} -le ${end_t} ]; do
# Print time in HH:MM format
date -d @${start_t} +"%H:%M"
# Increment minute part
start_t=$(expr ${start_t} + 60)
done