The system I am working with uses ssh to remotely connect to a Linux machine. It then executes a single shell command and analyses the output from the shell command.

If I run reboot, I get exit code -1, since rebooting of course kills the ssh connection. Any exit code other than 0 makes the system register a failure, thus I have been trying to write a single line command that will reboot and exit the ssh session gracefully.

The machines in question are very bare bones and the reboot utility does not allow any options so I can't just schedule a reboot for later.

After some thought I tried running

$ sleep 3 && reboot & exit

Which works when I call it manually: the connection closes with error code 0 and 3 seconds later the machine reboots. Great.

But the same command run through our system doesn't actually reboot. It just returns exit code 0 and the reboot never happens.

Why would this be?

  • I'm not certain why it's not working, but you could try ssh user@host "nohup init 6 < /dev/null > /dev/null 2>/dev/null". Alternatively, ssh user@host "nohup shutdown -r +1 > /dev/null 2>/dev/null" which will reboot the system one minute after the command is sent. – DopeGhoti Feb 22 '18 at 18:28

Use the shutdown command.

shutdown --reboot +1 "System is going down for reboot in 1 minute"

I suspect the reason reboot doesn't work is because it requires a tty. You could try running it with a background tty, but the shutdown command has everything you need, including cancelling -- as it says in response:

Shutdown scheduled for Thu 2018-02-22 15:19:33 MST, use 'shutdown -c' to cancel.
| improve this answer | |
  • 1
    That explains it, one minute is a little long to wait but it does work thanks. – YetAnotherRCG Feb 26 '18 at 19:19
  • Say now instead of +1 and change the message to suit. There isn't a way to specify a shorter interval (e.g. +15s would mean "in fifteen seconds"), but you can specify the next minute, so if it's 10:57 now, you could say 10:58 as your time specification. – Rich Mar 8 '18 at 17:57

Usually you can return true and that will return an exit code of 0 so:

shutdown -r now || true

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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