Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I am using Ubuntu 11.10.

I would like to make a shell script that shut down computer if nobody logins for an hour.

But if somebody logins (locally or with remote SSH connection), then i don't want to shut down computer..

And it would be highly appreciated if someone could let me know what should I do for applying that script.

Thank you very much!

share|improve this question

migrated from stackoverflow.com Apr 23 '12 at 22:33

This question came from our site for professional and enthusiast programmers.

1  
What have you tried? –  ghoti Apr 23 '12 at 2:23
1  
Asking about how to write a short shell script to do a specific thing is not the ideal SO question but it's reasonably close to the mainstream. Why close it? –  DigitalRoss Apr 23 '12 at 6:29

1 Answer 1

The desktop environment will have settings that control things like standby and hibernate power modes. This is usually good enough for simply saving electricity and putting the HD to sleep.

However, to answer the question you asked, a script could easily do a simple-minded check. To daemonize this script is slightly more involved but here is an example in Ruby to get you started:

last_user = Time.now
loop do
  last_user = Time.now if `who | wc -l`.to_i > 0
  system 'sudo shutdown -P +2' if Time.now - last_user >= 60 * 60
  sleep 10
end

It won't always detect brief logins less than 10 seconds as written...

It's a little bit clunkier in bash, especially without using && for if, but the equivalent is something like this:

last_user=`date +%s`
while :; do
  if [ `who | wc -l` -gt 0 ]; then
    last_user=`date +%s`
  fi
  if [ $((`date +%s` - $last_user)) -ge 3600 ]; then
    sudo shutdown -P +2
  fi
  sleep 10
done
share|improve this answer

Your Answer

 
discard

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