Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash date/time arithmetic

I have a little Bash script which suspends the computer after a given number of minutes. However, I'd like to extend it to tell me what the time will be when it will be suspended, so I can get a rough idea of how long time I have left so to speak.

#!/bin/sh
let SECS=$1*60
echo "Sleeping for" $1 "minutes, which is" $SECS "seconds."
sleep $SECS &&
pm-suspend

The only argument to the script will be how many minutes from now the computer should be suspended. All I want to add to this script is basically an echo saying e.g. "Sleeping until HH:nn:ss!". Any ideas?

like image 489
Deniz Dogan Avatar asked Jun 09 '09 01:06

Deniz Dogan


People also ask

What is %J in bash?

Using date. #!/bin/bash # Exercising the 'date' command echo "The number of days since the year's beginning is `date +%j`." # Needs a leading '+' to invoke formatting. # %j gives day of year. echo "The number of seconds elapsed since 01/01/1970 is `date +%s`." #

What is date +% s in bash?

date +%S. Displays seconds [00-59] date +%N. Displays in Nanoseconds.

How do I show time in bash?

Sample shell script to display the current date and time #!/bin/bash now="$(date)" printf "Current date and time %s\n" "$now" now="$(date +'%d/%m/%Y')" printf "Current date in dd/mm/yyyy format %s\n" "$now" echo "Starting backup at $now, please wait..." # command to backup scripts goes here # ...


3 Answers

Found out how.

echo "The computer will be suspended at" $(date --date "now $1 minutes")
like image 72
Deniz Dogan Avatar answered Oct 10 '22 23:10

Deniz Dogan


On BSD-derived systems, you'd use

date -r $(( $(date "+%s") + $1 * 60 ))

i.e. get the current date in seconds, add the number of minutes, and feed it back to date.
Yeah, it's slightly less elegant.

like image 38
Michiel Buddingh Avatar answered Oct 10 '22 23:10

Michiel Buddingh


on linux

SECS=`date "+$s"`
SECS=$(( SECS + $1 * 60 ))
date --date $SECS
like image 29
Chris Avatar answered Oct 11 '22 00:10

Chris