我有一个Bash脚本,通过它的API从网站下载文件,我想在最后实现一个东西(缺少更好的单词),这将显示脚本花了多长时间去完成。使用此代码,我能够做到:
JSON.stringify(data, null,4)
但是,这将显示脚本在一分钟内执行的时间:
#!/bin/bash
SECONDS=0
# -- Code to Execute --
echo "Task complete"
echo "Script completed in $(echo "scale=2; $SECONDS / 60" | bc) minutes"
我怎样才能将脚本完成的秒数转换为分钟和秒?像这样:
Task complete
Script completed in 1.35 minutes
答案 0 :(得分:5)
您可以在shell中使用整数除法和模运算符:
echo "Script completed in $((SECONDS/60)) minutes and $((SECONDS%60)) seconds"
如果你想省略秒和分钟零件,如果它们为零,那就有点复杂了:
if (( SECONDS/60 == 0 )); then
echo "Script completed in $SECONDS seconds"
elif (( SECONDS%60 == 0 )); then
echo "Script completed in $((SECONDS/60)) minutes"
else
echo "Script completed in $((SECONDS/60)) minutes and $((SECONDS%60)) seconds"
fi
(它仍会说“1分钟”而不是“1分钟”;如果你想让它变得更复杂,你也可以解决这个问题......)
答案 1 :(得分:3)
Bash擅长简单整数数学:
total_time=100
minutes=$((total_time / 60))
seconds=$((total_time % 60))
echo "Script completed in $minutes minutes and $seconds seconds"
# output -> Script completed in 1 minutes and 40 seconds