将bash / shell脚本时间格式化为天,小时,分钟和秒

时间:2014-08-12 09:59:07

标签: linux bash shell time formatting

我有一个用bash / shell脚本语言编写的备份脚本。我通过这样做来计算总运行时间/执行时间:

#!/bin/bash

# start time
res1=$(date +%s.%N)

### do some work here

# end time & calculate
res2=$(date +%s.%N)
dt=$(echo "$res2 - $res1" | bc)
dd=$(echo "$dt/86400" | bc)
dt2=$(echo "$dt-86400*$dd" | bc)
dh=$(echo "$dt2/3600" | bc)
dt3=$(echo "$dt2-3600*$dh" | bc)
dm=$(echo "$dt3/60" | bc)
ds=$(echo "$dt3-60*$dm" | bc)

# finished
printf " >>> Process Completed - Total Runtime (d:h:m:s) : %d:%02d:%02d:%02.4f\n" $dd $dh $dm $ds
echo " "
exit 0

这输出如下: enter image description here

如何格式化结果,所以它看起来像这样:

0天,0小时,0分钟和0.0968秒

如果它能够智能地仅显示值> 0,就像这些例子一样 - 它将是abonus:

  • 7分钟和5.126秒 或
  • 2小时,4分钟和1.106秒 或
  • 7.215秒等...

1 个答案:

答案 0 :(得分:4)

您可以使用上一个printf

printf " >>> Process Completed - Total Runtime (d:h:m:s) : %d Days, %02d Hours, %02d Minutes, %02.4f Seconds\n" $dd $dh $dm $ds

但是我建议您使用awk并在awk中进行所有计算和格式化,这样就可以避免多次调用bc

建议的awk脚本:

awk -v res1="$res1" -v res2="$res2" 'BEGIN {dt=res2-res1; dd=dt/86400; dt2=dt-86400*dd; 
      dh=dt2/3600; dt3=dt2-3600*dh; dm=dt3/60; ds=dt3-60*dm;
      printf " >>> Process Completed - Total Runtime (d:h:m:s) : %d Days, %02d Hours, %02d Minutes, %02.4f Seconds\n",
      dt/86400, dd, dh, dm, ds}'