First of all, welcome.
Although presentprevious answers here all satisfy the requirement to the perfection, I have a humble unsolicited suggestion, that's if you'd likeyou can also make your machine to 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
trapforEXITof your automated shell scripts, meaning termination of your automated tasks - Set a
trapfor your.bashrcEXIT, 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,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 lahla, cleaning is so nice
echo "Cy'a"See you later, world"
sudo poweroff & # finally shutdown
}
trap cleanup EXIT
This can be at the end of .bashrc for Optionoption #2, at somewhere at the top of your script for Optionoption #1.
Why not use poweroff at the end of the script?
I prefer to use set -eo pipefail inat on the top of my scripts, if. If any error happens, it won't silently fail,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 shutdownshut down before they are completed.
I have a simple bash template I use for making scripting easier to debug,debug; maybe it might be of some use. Please see this gist..