Bash date/time arithmetic
Asked Answered
N

3

7

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?

Nicholle answered 9/6, 2009 at 1:37 Comment(0)
N
10

Found out how.

echo "The computer will be suspended at" $(date --date "now $1 minutes")
Nicholle answered 9/6, 2009 at 1:37 Comment(4)
admit it; you just asked this question so you could answer it and get the "self-learner" badge. :-)Heydon
Haha, no, seriously. I think I already have that badge anyways? No, I didn't. No, but I just didn't think it was this easy.Nicholle
The first pair of quotes is superfluousZoochore
Shorter: date --date "$1 minutes" +'The computer will be suspended at %c'Zoochore
G
3

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.

Gopher answered 1/11, 2009 at 19:1 Comment(3)
@Chris I think formatting screwed you up there... there's no ending `Cryptoanalysis
deleted my back-ticks comment since it's part of an answer belowHuddleston
more interesting to me is the use of the $ syntax to execute the date function instead of single back quotes.Huddleston
H
1

on linux

SECS=`date "+$s"`
SECS=$(( SECS + $1 * 60 ))
date --date $SECS
Huddleston answered 24/7, 2013 at 3:29 Comment(2)
I think formatting screwed you up there... there's no ending `Cryptoanalysis
I added backslashes to escape the backticks. fixed.Huddleston

© 2022 - 2024 — McMap. All rights reserved.