How to shutdown ubuntu server from shell script?
Make sure the cron script is executable and also running as root, and replace shutdown
by its full path given to you by:
command -v shutdown
On Ubuntu GNU/Linux (and GNU/Linux in general), it should be /sbin/shutdown
:
#!/bin/bash
/sbin/shutdown -h now
Note that adding a file named like /etc/cron.d/midnight-shutdown
and containing:
59 23 * * * root test -x /sbin/shutdown && /sbin/shutdown -h now
should do what you want without the overhead of a full bash script. Here is the code to install this quickly:
echo '59 23 * * * root test -x /sbin/shutdown && /sbin/shutdown -h now' \
| sudo tee '/etc/cron.d/midnight-shutdow'
sudo service cron reload
EDIT: To reply to your comment, another possibility of setting is:
echo '59 23 * * * test -x /sbin/shutdown && /sbin/shutdown -h now' \
| sudo tee '/etc/cron.d/midnight-shutdown'
sudo service cron reload
It is quite strange that cron print you this error message.
Related videos on Youtube
qinking126
Updated on September 18, 2022Comments
-
qinking126 over 1 year
I wrote a simple shell script to shutdown an ubuntu server. Then I created a cron job to execute this script at 23:59 everyday.
#!/bin/bash sudo shutdown -h now
I got this error message:
sudo: no tty present and no askpass program specified
when I removed the sudo from the code, I got a different error message:
/home/qinking126/scripts/test.sh: line 3: shutdown: command not found
How do I resolve this?
-
qinking126 over 10 yearsgot this error message "/bin/sh: 1: root: not found"
-
Biapy over 10 yearsadded another setting possibility.