Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I need a script which will modify the system time by x amount of minutes. Something like:

#time = 12:56
#x = 2

if time_bool:
  time = time + x
  #time = 12:58
else:
  time = time - x
  #time = 12:54

It's apart of some Red Hat testing but may need to be moved to another OS (probably Fedora or CentOS).

share|improve this question
    
I guess you are aware that bad things have been known to happen when time goes backwards on a Unix/Linux system. –  RedGrittyBrick May 9 '12 at 9:10
    
Would you mind elaborating on bad things? My Linux systems experience is limited! My goal is to test a solution which involves multiple Linux boxes. One of the scripts involves randomly changing the time to see how it reacts. –  Federer May 9 '12 at 9:15
2  
Bad things: Processes that expect 12:03 to happen after 12:00, Cron jobs that run twice, programs that find something they just did has already happened in the future, children finding their parents died before they were born, lions lying down with sheep, the awakening of the old ones. –  RedGrittyBrick May 9 '12 at 10:06
add comment

2 Answers

up vote 3 down vote accepted

You could simply do

if $time_bool; then
    date --set="+${x} minutes"
else
    date --set="-${x} minutes"
fi

The date string syntax in GNU date is quite loose and permits many things.

Tested on Ubuntu.

share|improve this answer
add comment

A simple way might be:

date --set=@$(( $(date +%s) + 120 ))

(Untested)

But I can't guarentee this'll work between OS' since date +%s is an extension.

The script tries to get the current date UTC, convert this into seconds from the epoch, add 120 seconds, then set the date from Unix epoch seconds.

share|improve this answer
    
You can't nest backticks that way. Use $( ) instead, and $(( )) for the calculation. Note that --set is a GNU extension too, and it accepts the same formats as -d, so --set=@12345 should work directly. –  grawity May 9 '12 at 11:18
    
Good edit, thanks for that. Why is it necessary to use double brackets for the calculation? –  deed02392 May 12 '12 at 9:03
1  
Because $( and $(( are two different operators. $( runs a process, $(( performs calculations. The operator itself is needed because date does not perform calculations itself if you give it a @timestamp. –  grawity May 12 '12 at 10:34
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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