I'm trying to run a simple bash script that turns off my notebook if it is not pluged on AC with a cron job.
My script is as follows:
#!/bin/bash
if ! on_ac_power; then
poweroff
fi
And I've configured cron to run it every minute like so:
*/1 * * * * /home/user/Documents/script.sh
The script works just fine if I run it manually, but otherwise, it seems to have no effect under cron.
What am I missing here?
on_ac_power? it gives nothing when on ac and when not on ac so seems useless for this. And poweroff I would add a directory to. – Rinzwind Aug 23 '21 at 15:31on_ac_powertests whether the computer is running on line power. Add a directory do poweroff, how so? As I said the script works just fine if I run it manually, but cron seems to not be running it. – Rogerio Schmitt Aug 23 '21 at 15:43poweroffshould require root privileges;sudo poweroffmight work if the user in question is not required to enter a password. Better yet, put the cron entry into/etc/crontaband specify that it's to be executed asroot(of course, the script should be moved to a sensible location as well in that case). – Markus Ueberall Aug 23 '21 at 15:45sudoin scripys and never ever in thingd that have ti be run in cron !! Instead run the script in root's cron if needed. – Soren A Aug 23 '21 at 16:05poweroff(/usr/sbin/poweroff) liks to /bin/systemctl wgich can be executed by anyone sosudoisn't needed anyway. – Soren A Aug 23 '21 at 16:11/bin/systemctlcan be executed by anyone, but executingpoweroffas a non-root user will not necessarily work if other users are logged in (seepoweroff -i, which I actually forgot to mention above);sudo poweroffalways works immediately. – Markus Ueberall Aug 23 '21 at 16:23sudodoesn't worke in crontab ... the script must be run in root's cron. And for logged in users, there are seldom more than one user logged in on home systems . but off course a point to be aware of on larger systems. – Soren A Aug 23 '21 at 16:46sudodoes work in crontab as long as you don't need to enter a password (see e.g. https://askubuntu.com/questions/796617/how-to-avoid-password-request-for-sudo-for-crontab-scripts); whether it's a good idea to use it for the OP's use case is another question (see previous comments pointing to a service and/etc/crontabaddressing this). – Markus Ueberall Aug 24 '21 at 07:07