0

I want to display the duration of a command in my script. Depeding the duration I want somethng like this: 12 minutes 04 seconds or 01 hours 15 minutes 02 seconds. Always with a leading zero.

I tried different things I found here, but didn't get the result.

BTW: that's my first try in the bash.

Community
  • 1
  • 1
Gurkenglas
  • 33
  • 4

2 Answers2

1
#!/bin/bash
DATE1=$(date +%s)  
# ... your commands 
DATE2=$(date +%s)
DIFF=$(awk -vdate1=$DATE1 -vdate2=$DATE2 'BEGIN{print strftime("%H hour %M minutes %S seconds",date2-date1,1)}')
echo $DIFF

Time is converted to seconds and stored in variables DATE1 and DATE2 pre-condition DATE2 > DATE1

DATE1=$(date +%s)  
# ... your commands 
DATE2=$(date +%s)

strftime is used to get time-diff in seconds and formatted 1 is passed as 3rd argument as UTC Flag

strftime("%H hour %M minutes %S seconds",date2-date1,1)
Chet
  • 1,205
  • 1
  • 12
  • 20
  • Thank you for the help. I tried different versions and this one is great for me: ` start_time=$(date +"%s") # do my commands end_time=$(date +"%s") duration=$(($end_time-$start_time)) hours=$(printf '%02d' "$(($duration /3600 ))") minutes=$(printf '%02d' "$((($duration % 3600) / 60))") seconds=$(printf '%02d' "$(($duration % 60))") if [ $hours -eq 0 ] then com_time=$(printf "$minutes:$seconds minutes") else com_time=$(printf "$hours:$minutes hours") fi ยด โ€“ Gurkenglas Jun 07 '16 at 15:52
0

You could use the time executable (not the bash builtin because the external program features the format option -f and delivers the time as [hours:]minutes:seconds and I am not in the mood right now to wait an hour to find out how the builtin shows us the hours :) ) and awk like this (using the example sleep 2):

/usr/bin/time -f "%E" sleep 2 2> >( 
   awk -F : ' 
    { if(FN>2) printf("%02d hours %02d minutes %02d seconds\n", $1, $2, $3)
      else printf("%02d minutes %02d seconds\n", $1, $2) 
    }' 
)

Here we use /usr/bin/time with its -f option. Then we pipe the output of stderr into awk splitting the string at :. (time writes to stderr, thus we need the 2> to redirect stderr into the >( awk ... ) filter.

The awk filter decides on the number of fields in NF what printf statement it is using.

Lars Fischer
  • 9,135
  • 3
  • 26
  • 35
  • That sounds cool. My command to check the time is multible lines long. In your example only `sleep 2`. How can I add my command in ist own lines? โ€“ Gurkenglas Jun 05 '16 at 15:51
  • @Gurkenglas: first idea: put your commands into a script of its own and time that script; second idea: use Chets solution. I tried to put `cmd1; cmd2` into the sleeps place and `(cmd1; cmd2)`; nothing worked. โ€“ Lars Fischer Jun 05 '16 at 17:38