How can I invoke poweroff from a script/process?

I’d like for my droplet image to do the following:

  • Boot Ubuntu 20
  • Start a process (using services.d or whatever)
  • When the process finishes, invoke poweroff
  • For the droplet to truly power off

I haven’t been able to make this work. The poweroff command works from the CLI, if I am logged in as a user, even if the user is not a sudoer.

But if noone is logged onto the CLI, and the task finishes without a user being logged into the shell, the poweroff command appears to have no effect.

How do I power off a droplet programmatically from a bash script?


Submit an answer
You can type!ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

The following at first seemed to enable poweroff from userland:

sudo chmod a+s /usr/sbin/poweroff

… However I was not able to reliably make this work without a logged in shell user present.

What I’m doing now, instead, is:

# User script:
./my-script ; touch /tmp/.poweroff;

# Root crontab:
* * * * * stat /tmp/.poweroff && /usr/sbin/poweroff;