Execute Script when starting Ubuntu

3

I want that when I start Ubuntu 16.04, I automatically run a script, so far I have the following:

script.sh:

#!/bin/bash
mkdir prueba_carpeta

and what I have done to run automatically is as follows:

  • I give you permission.

    sudo chmod +x script.sh
    
  • I add it in the rc.local

    sudo nano /etc/rc.local
    

rc.local

#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
sh /var/www/html/script.sh
exit 0

But it does not work, I also tried:

sudo mv /var/www/html/script.sh /etc/init.d/
sudo chmod +x /etc/init.d/script.sh 
sudo update-rc.d script.sh defaults

But it did not work either, I clarify that after performing each form, I restart the S.O. , I also clarify that when I run the script in the console, it works.

    
asked by Andrés 18.07.2017 в 17:03
source

2 answers

3

With respect, Cesar's response is valid but not the most efficient. If you want to run the script during system startup, you have to add a symbolic link in the /etc/rc.d/ directory:

Command to create the symbolic link in your case:

ln -s /var/www/html/script.sh /etc/rc.d/.

You can also solve your problem by putting the absolute path of the program, that is, use in your script mkdir /var/www/html/prueba_carpeta instead of mkdir prueba_carpeta .

Keep in mind that this system is more efficient (in most cases), but in the latest versions of some OS (the latest versions of Debian for example), you have to include the options start , stop , restart , force-reload , and status in your script.

In case you find out that the directory '/ etc / rc.d' does not exist execute runlevel , this results in a number (from 1 to 6), taking into account the number executes the command ln -s /var/www/html/script.sh /etc/rc?.d/. changing the ? to the number that came out earlier (when executing runlevel )

    
answered by 18.07.2017 / 17:21
source
2

You can use a Cron job to run on restart. It is likely that the implementation of your operating system supports the macros @reboot (it is most likely, I had some problems with other Linux distributions). What you have to do is edit the crontab of your user:

$ crontab -e

And add the path of your script using @reboot :

@reboot /var/www/html/script.sh

It's the simplest thing, I use it all the time.

    
answered by 18.07.2017 в 17:08