Bash: subtracting 10 mins from a given time

后端 未结 4 1631
佛祖请我去吃肉
佛祖请我去吃肉 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:45

    My version of bash doesn't support -d or --date as used above. However, assuming a correctly 0-padded input, this does work

    $ input_time=130503 # meaning "1:05:03 PM"
    
    # next line calculates epoch seconds for today's date at stated time
    $ epoch_seconds=$(date -jf '%H%M%S' $input_time '+%s')
    
    # the 600 matches the OP's "subtract 10 minutes" spec. Note: Still relative to "today"
    $ calculated_seconds=$(( epoch_seconds - 600 )) # bc would work here but $((...)) is builtin
    
    # +%H%M%S formats the result same as input, but you can do what you like here
    $ echo $(date -r $calculated_seconds '+%H%M%S')
    
    # output is 125503: Note that the hour rolled back as expected.
    

提交回复
热议问题