2

Shell

How can I write a shell script, using only shell features (and the date command), to output the number of minutes that have elapsed in the current day?

4

Since date treats non-specifiers as literals you could use the format string to construct a simple arithmetic expression for the current number of minutes, and then evaluate the result using the shell's built-in arithmetic. For example, in bash

printf "$(( $(date '+%H * 60 + %M') ))\n"

If your shell does not support arithmetic, you could use an external calculator such as bc

date '+%H * 60 + %M' | bc

or dc

date '+%H 60 * %M + p' | dc
2

GNU date and bash:

daystart_sec="$(date --date="today 00:00:00" +%s)"
now_sec="$(date +%s)"
echo $(((now_sec-daystart_sec)/60))
-1

how do I subtract the number of minutes passed in the day from the number of minutes left in the day (i.e., 1440)? So basically I want to subtract the output of the above from 1440.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.