-1

I have these two funtions in my bash script

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 "
}

So I execute them in the following way;

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

If the script takes for example, 3 hrs 23 minutes 50 seconds, it shows of the following way the output

execution time was : 3 hours 203 minutes and 50 seconds

So, my question is, whether there is some way to show the correct minutes, i mean the 123 minutes are the total time that the script took in execute some job, so the expected output must be : 3 hours 23 minutes 50 seconds.

shaveax
  • 448
  • 5
  • 15
  • It looks like your hours rounded up there, it should presumably be 2 hours and 3 minutes. Since 123 minutes is a little more than 2 hours. – Elliott Frisch Mar 30 '16 at 18:58
  • Do you need hours displayed or could you simply just use minutes and seconds? – IT_User Mar 30 '16 at 18:59
  • http://stackoverflow.com/questions/8903239/how-to-calculate-time-difference-in-bash-script – IT_User Mar 30 '16 at 18:59
  • 1
    Did you actually get `3 hours 123 minutes and 50 seconds` as output from something? Because that shouldn't be possible I don't think. The problem here is that you aren't subtracting the whole hours from the `minutes` value. – Etan Reisner Mar 30 '16 at 19:02
  • try this: `minutes=$(( (diff / 60) %60 ))` – F. Hauri Mar 30 '16 at 19:04
  • you could print elpsed time by `printf "%(%j %T)T\n" $diff` (by substracting 1 day) – F. Hauri Mar 30 '16 at 19:07
  • this works perfectly for my: minutes=$(( (diff / 60) %60 )), thanks a lot @ F. Hauri – shaveax Mar 30 '16 at 19:11
  • 1
    Take a look at bash's special variable SECONDS: `SECONDS=0; sleep 3; echo $SECONDS` – Cyrus Mar 30 '16 at 19:19

1 Answers1

1

Why re-invent the wheel? the time command will already do what you want:

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

(This is using command time instead of time to make sure that you are not calling some shell built-in)

umläute
  • 26,106
  • 8
  • 56
  • 114
  • 2
    `which` isn't standardized, may not be present and shell-ing to find it is (relatively( expensive. The shell provides a `command` built-in for this exact purpose. – Etan Reisner Mar 30 '16 at 19:01