Although previous answers here all satisfy the requirement to perfection, you can also make your machine power off as soon as the tasks are done.
bash
scripts can be trap
ped, meaning certain signals can be intercepted and certain tasks can be executed when needed. EXIT
is one of the signals that can be trapped.
You would be able to:
- Set a
trap
for EXIT
of your automated shell scripts, meaning
termination of your automated tasks
- Set a
trap
for your .bashrc
EXIT
, meaning whenever you log out
of that machine, power it off.
Option #1 would be the ideal case, provided your tasks don't require adhoc inspection and manual judgement.
Option #2 would cover the cases where you'd forget to exit the terminal without powering off. There is a caveat though; if you have multiple terminals to the same machine open and you exit from one of them, it will still power off the machine all the same. (It can be scripted to avoid that, but I won't complicate the solution.)
cleanup(){
# Do some tasks before terminating
echo oh la la, cleaning is so nice
echo "See you later, world"
sudo poweroff & # finally shutdown
}
trap cleanup EXIT
This can be at the end of .bashrc
for option #2, at somewhere at the top of your script for option #1.
Why not use poweroff
at the end of the script?
I prefer to use set -eo pipefail
at on the top of my scripts. If any error happens, it won't silently fail; it will stop executing more commands. trap
of EXIT
signal should cover the cases where the script terminates prematurely due to errors.
However for your tasks, this might also mean the machine will shut down before they are completed.
I have a simple bash
template I use for making scripting easier to debug; maybe it might be of some use. Please see this gist.
at
(one-time execution).sudo shutdown -h +60
which would start a countdown counter of 60 mins for the shutdown (-halt) process. If you wanted to cancel it, you couldsudo shutdown -c
(this doesn't use cron though)