Peter S.
Peter S.

Reputation: 23

How can I trigger a delayed system shutdown from in a shell script?

On my private network I have a backup server, which runs a bacula backup every night. To save energy I use a cron job to wake the server, but I haven't found out, how to properly shut it down after the backup is done. By the means of the bacula-director configuration I can call a script during the processing of the last backup job (i.e. the backup of the file catalog). I tried to use this script:

#!/bin/bash
# shutdown server in 10 minutes
#
# ps, 17.11.2013
bash -c "nohup /sbin/shutdown -h 10" &
exit 0

The script shuts down the server - but apparently it returns just during the shutdown, and as a consequence that last backup job hangs just until the shutdown. How can I make the script to file the shutdown and return immediately?

Update: After an extensive search I came up with a (albeit pretty ugly) solution: The script run by bacula looks like this:

#!/bin/bash
at -f /root/scripts/shutdown_now.sh now + 10 minutes

And the second script (shutdown_now.sh) looks like this:

#!/bin/bash
shutdown -h now

Actually I found no obvious method to add the required parameters of shutdown in the syntax of the 'at' command. Maybe someone can give me some advice here.

Upvotes: 2

Views: 9506

Answers (3)

Aaron
Aaron

Reputation: 459

If you can become root: either log in as, or sudo -i this works (tested on ubuntu 14.04):

# shutdown -h 20:00 & //halts the machine at 8pm

No shell script needed. I can then log out, and log back in, and the process is still there. Interestingly, if I tried this with sudo in the command line, then when I log out, the process does go away!

BTW, just to note, that I also use this command to do occasional reboots after everyone has gone home.

# shutdown -r 20:00 & //re-boots the machine at 8pm

Upvotes: 0

Brian Showalter
Brian Showalter

Reputation: 4349

No need to create a second BASH script to run the shutdown command. Just replace the following line in your backup script:

bash -c "nohup /sbin/shutdown -h 10" &

with this:

echo "/sbin/poweroff" | /usr/bin/at now + 10 min >/dev/null 2>&1

Feel free to adjust the time interval to suit your preference.

Upvotes: 3

Chriki
Chriki

Reputation: 16408

Depending on your backup server’s OS, the implementation of shutdown might behave differently. I have tested the following two solutions on Ubuntu 12.04 and they both worked for me:

As the root user I have created a shell script with the following content and called it in a bash shell:

shutdown -h 10 &
exit 0

The exit code of the script in the shell was correct (tested with echo $?). The shutdown was still in progress (tested with shutdown -c).

This bash function call in a second shell script worked equally well:

my_shutdown() {
  shutdown -h 10
}
my_shutdown &
exit 0

Upvotes: 4

Related Questions