Cron job to power off when AC is unplugged not running

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?


Solution 1:

First of all I was not running my cron under root.

Apparently for a cron to run under root you have to add it with sudo crontab -e, anything added just with crontab -e will not run as sudo.

Second as pointed in the reference:

cron runs in a very limited environment by default so a lot of commands that run via command name from a users terminal need to the full path in a crontab or a declaration at the beginning of the crontab to expand the path.

So I ended up replacing poweroff by /sbin/shutdown in my script, and now it runs as expected.

#!/bin/bash

if ! on_ac_power; 
then 
    /sbin/shutdown        
fi

Reference