Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 Apr 23 '12 at 22:33

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

What have you tried? – ghoti Apr 23 '12 at 2:23
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

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 =
loop do
  last_user = if `who | wc -l`.to_i > 0
  system 'sudo shutdown -P +2' if - last_user >= 60 * 60
  sleep 10

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`
  if [ $((`date +%s` - $last_user)) -ge 3600 ]; then
    sudo shutdown -P +2
  sleep 10
share|improve this answer

Your Answer


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