Sam
Sam

Reputation: 13

Subtraction in bash

printf "$(( $(date '+%H * 60 + %M') ))\n"
date '+%H * 60 + %M' | bc
date '+%H 60 * %M + p' | dc

The above will give the minutes that have passed in the day.

Using any of the above time outputs, how do I subtract it from the total minutes in the day (i.e., 1440) to display the minutes left in the day?

Upvotes: 1

Views: 121

Answers (3)

Jamil Said
Jamil Said

Reputation: 2083

You could use something like this:

minutesElapsed="$(date '+%H * 60 + %M' | bc)"
minutesDay="1440" 
minutesLeft="$(($minutesDay-$minutesElapsed))"

Output:

echo "$minutesLeft"
332

Short version:

echo "$((1440-$(date '+%H * 60 + %M' | bc)))"

Upvotes: 0

Ruslan Osmanov
Ruslan Osmanov

Reputation: 21492

The following computes the difference of timestamps in minutes:

printf '%d\n' $(( ( $(date -d 'tomorrow 00:00' '+%s') - $(date '+%s') ) / 60 ))

Note the use of format string %d\n. You shouldn't pass your data in the first argument for printf, as the first argument is the format string, and printf may interpret some sequences as the format specifiers (%d as integer specifier, %s as string specifier, etc.).

Upvotes: 0

Jonathan Leffler
Jonathan Leffler

Reputation: 753495

Given your three exemplars, what about:

printf "$(( 1440 - ( $(date '+%H * 60 + %M') ) ))\n"
date '+1440 - ( %H * 60 + %M )' | bc
date '+1440 %H 60 * %M + - p' | dc

You don't quite need all the spaces added, but you do need the added parentheses.

Upvotes: 2

Related Questions