Run Bash script as root in startup on ubuntu 18.04

Viewed 11628

I wanted to run a bash script as root in startup. First I started using RC.Local and Crontab but nothing works.

4 Answers

Create the service file as in the template below and add the file in the location /etc/systemd/system/

And the Template as

[Unit]
Description = ~Name of the service~

[Service]
WorkingDirectory= ~directory of working file~
ExecStart= ~directory~/filename.sh

[Install]
WantedBy=multi-user.target

Start the service file by the name using

systemctl start servicefile.service

To enable on startup

systemctl enable servicefile.service

To check the status

systemctl status servicefile.service

To stop

systemctl stop servicefile.service

Create a systemd unit file in /etc/systemd/system/ and use it to execute your script. (i.e. hello-world.service).

[Unit]
Description=Hello world
After=sysinit.target
StartLimitIntervalSec=0

[Service]
Type=simple
Restart=no
RemainAfterExit=yes
User=root
ExecStart=/bin/echo hello world
ExecStop=/bin/echo goodby world

[Install]
WantedBy=multi-user.target

Now you can use it through systemctl as you would with other services.

$ systemctl enable hello-world
$ systemctl start hello-world
$ systemctl stop hello-world
$ systemctl status hello-world
ā— hello-world.service - Hello world
   Loaded: loaded (/etc/systemd/system/hello-world.service; enabled; vendor preset: enabled)
   Active: inactive (dead) since Wed 2019-10-09 13:54:58 CEST; 1min 47s ago
  Process: 11864 ExecStop=/bin/echo goodby world (code=exited, status=0/SUCCESS)
 Main PID: 11842 (code=exited, status=0/SUCCESS)

Oct 09 13:54:38 lnxclnt1705 systemd[1]: Started Hello world.
Oct 09 13:54:38 lnxclnt1705 echo[11842]: hello world
Oct 09 13:54:57 lnxclnt1705 systemd[1]: Stopping Hello world...
Oct 09 13:54:57 lnxclnt1705 echo[11864]: goodby world
Oct 09 13:54:58 lnxclnt1705 systemd[1]: Stopped Hello world.

Make sure that you use the full path to your script in the unit file (i.e. /bin/echo). Check out the documentation about keys used in hello-world.service:

Place the script inside /etc/init.d

Ensure that it has the extension '.sh'

For the crontab,

there is difference in if you set up user crontab or root crontab:

$ crontab -e 

@reboot sudo ...

^^ This is user's cron tab and wont work as it is.

$ sudo crontab -e

@reboot ...

^^ This is root's cron tab and will run comand as root.

The @reboot should do the trick for you of running scripts after startup.

Related