Progmar Marcin Załęczny

Language:

How to create script that is executed during Ubuntu 15.04 startup

Since 15.04 Ubuntu version it uses systemd as a startup daemon. Here is how to make a script run during system startup. You need two files to make it happen. First is your script file, for example iptables.sh bash script that sets firewall rules and the second is so called service file.

  • Put the iptables.sh file (or symlink to the real file) into the /usr/lib/systemd/scripts directory. Make the script executable (755).
  • Then create a new plain text service file in /usr/lib/systemd/system directory. Let's call it iptables_sh.service. Fill it with the content below:
    [Unit]
    Description=Iptables firewall
    
    [Service]
    Type=oneshot
    ExecStart=/usr/lib/systemd/scripts/iptables.sh
    
    [Install]
    WantedBy=multi-user.target
  • And finally issue the command: sudo systemctl enable iptables_sh.service From now then the script will be executed during system startup.

In case your script is parameterized with start/stop arguments, ex.:

start() {
  command_1;
  command_2;
  ...
}

stop() {
  command_3;
  command_4;
  ...
}

case $1 in
  start|stop) "$1" ;;
esac
then your service file should look like below:
[Unit]
Description=Iptables firewall

[Service]
Type=oneshot
ExecStart=/usr/lib/systemd/scripts/iptables.sh start
ExecStop=/usr/lib/systemd/scripts/iptables.sh stop
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target