bashparsingtime

How to convert time period string in sleep format to seconds in bash


This is about a time string in the format accepted by the common linux command sleep, like "3d 7h 5m 10s" (3 days, 7 hours, 5 minutes and 10 seconds), which would have to result in:

(3 * 24 * 60 * 60) + (7 * 60 * 60) + (5 * 60) + 10 = 284710 seconds

Note that not all these 4 elements must be present, nor in the right order, and one element might appear multiple times. So "3s 5s 6h" is valid too, and should result in:

(6 * 60 * 60) + (3 + 5) = 21608 seconds


Solution

  • When you replace the letters with the corresponding factors, you can pipe that to bc. You only need to take care of the + at the end of the line.

    t2s() {
       sed 's/d/*24*3600 +/g; s/h/*3600 +/g; s/m/*60 +/g; s/s/\+/g; s/+[ ]*$//g' <<< "$1" | bc
    }
    

    Testrun

    $ t2s "3d 7h 5m 10s"
    284710
    $ t2s "3d 7h 5m "
    284700
    $ t2s "3s 5s 6h"
    21608