Solutions
Without further ado, let’s give execute permission to your script:
$ chmod +x YOUR_SCRIPT.sh
Now let’s see how to schedule its execution.
1. Using cron
Let’s begin with the easiest solution, which involves using cron. In order to do this, we need to edit our crontab file:
$ crontab -e
Here we’ll add a line using the @reboot expression, which will execute our code once at startup:
@reboot sh /home/ec2-user/YOUR_SCRIPT.sh
This solution is quick and clean, since we don’t have to deal with additional configuration, but not every version of cron supports @reboot.
2. Using rc.local
Now let’s consider another solution that takes advantage of the /etc/rc.d/rc.local file. Since this file already runs at startup, we can append a line that invokes our script:
sh /home/ec2-user/YOUR_SCRIPT.sh
In order for this to work, we need to ensure that the rc.local file itself is executable:
$ chmod +x /etc/rc.d/rc.local
3. Using init.d
Similar to the previous solution, the /etc/init.d folder contains lifecycle executables of the services managed by the system. We can also add our own by creating an LSB-compliant wrapper that starts our service:
#! /bin/sh
# chkconfig: 345 99 10
case "$1" in
start)
# Executes our script
sudo sh /home/ec2-user/YOUR_SCRIPT.sh
;;
*)
;;
esac
exit 0
This wrapper will launch our code when it’s invoked with the start argument. However, we must include a line with the chkconfig configuration, which contains the service runlevel and the start/stop priority.
After placing the wrapper in the init.d folder, we need to register our service for startup execution:
$ chkconfig --add service_wrapper.sh
Since the chkconfig command isn’t available on Debian systems, update-rc.d can be used as an alternative there:
$ update-rc.d service_wrapper.sh defaults
Hope it helps, if yes, please upvote.
init.d
solution (here) should be preferred to therc.local
solution because the latter one is the old tooling which is only still usable because the new tooling is backward compatible. – Toluca