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
trapped, 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
EXIT of your automated shell scripts, meaning
termination of your automated tasks
- Set a
trap for your
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.)
# 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.
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.