Sometimes it may be necessary to run certain commands or scripts at restart time or every time the system starts. What are we going to do? We'll discuss this in this article. We'll use two methods to describe how to reboot on Centos/rhel and Ubuntu systems or execute commands and scripts when the system starts. Both methods pass the test.
This article navigation? Method Use Rc.local14%? Method-Use Crontab61%Compiled from | http://linuxtechlab.com/executing-commands-scripts-at-reboot/
Author | Shusain
Translator | lujun9972
Sometimes it may be necessary to run certain commands or scripts at restart time or every time the system starts. What are we going to do? We'll discuss this in this article. We'll use two methods to describe how to reboot on Centos/rhel and Ubuntu systems or execute commands and scripts when the system starts. Both methods pass the test.
Method Use Rc.local
This method uses /etc/
the files in rc.local
to execute scripts and commands at startup. We add a line to the file to execute the script, which is executed every time the system is started.
But first we need to /etc/rc.local
add Execute permissions,
$ sudo chmod +x /etc/rc.local
Then add the script you want to execute:
$ sudo vi /etc/rc.local
At the end of the document, add:
sh /root/script.sh &
Then save the file and exit. Using the rc.local
file to execute the command is the same, but be sure to fill in the full path of the command. To know the full path of the command can be run:
$ which command
Like what:
$ which shutter
/usr/bin/shutter
If it's CentOS, we're modifying the file /etc/rc.d/rc.local
instead /etc/rc.local
. But we also need to add executable permissions to the file first.
Note:-Scripts executed at startup, please be sure to end with exit 0
.
Method-Use Crontab
The method is the simplest. We create a cron task that waits 90 seconds after the system starts, then executes commands and scripts.
To create a cron task, open the terminal and execute
$ crontab -e
Then enter the downstream content,
@reboot ( sleep 90 ; sh \location\script.sh )
This \location\script.sh
is the address of the script to be executed.
Execute commands and scripts on Linux startup or restart