【问题标题】:how to set the time correctly in bash? [duplicate]如何在bash中正确设置时间? [复制]
【发布时间】:2016-03-30 18:44:27
【问题描述】:

我的 bash 脚本中有这两个函数

function start_time {
  unset date1
  date1=$(date +"%s")
}

function stop_time {
  unset date2 diff minutes seconds hours varhours varminutes varseconds
  date2=$(date +"%s")
  diff=$(($date2-$date1))   # <-- There is seconds
  minutes=$((($diff / 60)))
  seconds=$((($diff % 60)))
  hours=$((($minutes / 60)))

  if [ $hours != 0 ]; then varhours=$(echo "$hours Hours"); fi
  if [ $minutes != 0 ]; then varminutes=$(echo "$minutes Minutes"); fi
  if [ $seconds != 0 ]; then varseconds=$(echo "$seconds Seconds"); fi

  echo "++ $1 : $varhours $varminutes $varseconds "
}

所以我按以下方式执行它们;

start_time    
"some bash job for example sleep command for a while"
stop_time "execution time was"

如果脚本占用例如 3 小时 23 分 50 秒,它会以以下方式显示输出

执行时间:3小时203分50秒

所以,我的问题是,是否有某种方法可以显示正确的分钟数,我的意思是 123 分钟是脚本执行某项工作的总时间,所以预期的输出必须是:3 小时 23 分钟 50秒。

【问题讨论】:

  • 看起来你的小时数在那里四舍五入,大概应该是 2 小时 3 分钟。因为 123 分钟比 2 小时多一点。
  • 您需要显示小时还是只使用分钟和秒?
  • 你真的得到了3 hours 123 minutes and 50 seconds作为输出吗?因为那不应该是可能的,我不认为。这里的问题是您没有从 minutes 值中减去整个小时数。
  • 看看bash的特殊变量SECONDS:SECONDS=0; sleep 3; echo $SECONDS

标签: bash shell ubuntu command-line


【解决方案1】:

为什么要重新发明轮子? time 命令已经可以做你想做的事了:

command time --format "execution time was :%E" sleep 100

(这是使用command time 而不是time 以确保您没有调用一些内置的shell)

【讨论】:

  • which 不是标准化的,可能不存在,并且可以通过外壳找到它(相对(昂贵。外壳提供了一个 command 内置用于此确切目的。跨度>
猜你喜欢
  • 2014-05-11
  • 1970-01-01
  • 2019-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-24
相关资源
最近更新 更多