Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Bash script as root in startup on ubuntu 18.04

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

like image 322
Sujikanth Avatar asked Oct 09 '19 10:10

Sujikanth


2 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
like image 61
Bubashan_kushan Avatar answered Sep 23 '22 06:09

Bubashan_kushan


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:

  • [Unit]
  • [Service]
like image 30
Bayou Avatar answered Sep 25 '22 06:09

Bayou