Bash:以天、小时、分钟、秒显示秒



我有一个受hms启发的函数,但我希望将其扩展到包括处理和显示Days。

我已经开始编辑剧本了,但很快就意识到我对处理逻辑已经力不从心,时间一天一小时,反之亦然。。。

到目前为止,我拥有的是:

#!/bin/bash
rendertimer(){
# convert seconds to Days, Hours, Minutes, Seconds
# thanks to https://www.shellscript.sh/tips/hms/
local seconds D H M S MM D_TAG H_TAG M_TAG S_TAG
seconds=${1:-0}
S=$((seconds%60))
MM=$((seconds/60)) # total number of minutes
M=$((MM%60))
H=$((MM/60))
D=$((H/24))
# set up "x day(s), x hour(s), x minute(s) and x second(s)" format
[ "$D" -eq "1" ] && D_TAG="day" || D_TAG="days"
[ "$H" -eq "1" ] && H_TAG="hour" || H_TAG="hours"
[ "$M" -eq "1" ] && M_TAG="minute" || M_TAG="minutes"
[ "$S" -eq "1" ] && S_TAG="second" || S_TAG="seconds"
# logic for handling display
[ "$D" -gt "0" ] && printf "%d %s " $D "${D_TAG},"
[ "$H" -gt "0" ] && printf "%d %s " $H "${H_TAG},"
[ "$seconds" -ge "60" ] && printf "%d %s " $M "${M_TAG} and"
printf "%d %sn" $S "${S_TAG}"
}
duration=${1}
howlong="$(rendertimer $duration)"
echo "That took ${howlong} to run."

所需输出

CCD_ 2秒:";这花了4天1小时1分1秒的时间">

CCD_ 3秒:";这花了1天11小时32分12秒的时间">

CCD_ 4秒:";这花了1天的时间">

实际输出

CCD_ 5秒:";这花了4天97小时1分1秒的时间">

CCD_ 6秒:";这花了1天35小时32分12秒的时间">

CCD_ 7秒:";这花了1天24小时0分0秒的时间">

有人能帮我弄清楚吗?

更换

H=$((MM/60))
D=$((H/24))

H=$((MM/60%24))
D=$((MM/60/24))

所以,天是总分钟数的商,小时是总分钟的模数。

另外,你的第二个例子是错误的。127932的期望输出是That took 1 day, 11 hours, 32 minutes and 12 seconds to run

感谢@BeardOverflow和@NikolaySidorov,这很好:

#!/bin/bash
rendertimer(){
# convert seconds to Days, Hours, Minutes, Seconds
# thanks to Nikolay Sidorov and https://www.shellscript.sh/tips/hms/
local parts seconds D H M S D_TAG H_TAG M_TAG S_TAG
seconds=${1:-0}
# all days
D=$((seconds / 60 / 60 / 24))
# all hours
H=$((seconds / 60 / 60))
H=$((H % 24))
# all minutes
M=$((seconds / 60))
M=$((M % 60))
# all seconds
S=$((seconds % 60))
# set up "x day(s), x hour(s), x minute(s) and x second(s)" language
[ "$D" -eq "1" ] && D_TAG="day" || D_TAG="days"
[ "$H" -eq "1" ] && H_TAG="hour" || H_TAG="hours"
[ "$M" -eq "1" ] && M_TAG="minute" || M_TAG="minutes"
[ "$S" -eq "1" ] && S_TAG="second" || S_TAG="seconds"
# put parts from above that exist into an array for sentence formatting
parts=()
[ "$D" -gt "0" ] && parts+=("$D $D_TAG")
[ "$H" -gt "0" ] && parts+=("$H $H_TAG")
[ "$M" -gt "0" ] && parts+=("$M $M_TAG")
[ "$S" -gt "0" ] && parts+=("$S $S_TAG")
# construct the sentence
result=""
lengthofparts=${#parts[@]}
for (( currentpart = 0; currentpart < lengthofparts; currentpart++ )); do
result+="${parts[$currentpart]}"
# if current part is not the last portion of the sentence, append a comma
[ $currentpart -ne $((lengthofparts-1)) ] && result+=", "
done
echo "$result"
}
duration=$1
howlong="$(rendertimer "${duration}")"
echo "That took ${howlong} to run."

最新更新