Bash: subtracting 10 mins from a given time

后端 未结 4 1634
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-14 08:02

In a bash script, if I have a number that represents a time, in the form hhmmss (or hmmss), what is the best way of subtracting 10 minutes?

ie, 90000 -> 85000

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-14 08:55

    Since you have a 5 or 6 digit number, you have to pad it before doing string manipulation:

    $ t=90100
    $ while [ ${#t} -lt 6 ]; do t=0$t; done
    $ echo $t
    090100
    $ date +%H%M%S --utc -d"today ${t:0:2}:${t:2:2}:${t:4:2} UTC - 10 minutes"
    085100
    

    Note both --utc and UTC are required to make sure the system's timezone doesn't affect the results.

    For math within bash (i.e. $(( and ((), leading zeros will cause the number to be interpreted as octal. However, your data is more string-like (with a special format) than number-like, anyway. I've used a while loop above because it sounds like you're treating it as a number and thus might get 100 for 12:01 am.

提交回复
热议问题