Sometimes it may be necessary to run certain commands or scripts at restart or every time the system starts. How do we do this? In this article we discuss this. We will use two methods to describe how to restart or execute commands and scripts at system startup on CentOS/RHEL and Ubuntu systems. Both methods passed the test.
This method will use the rc.local file in /etc/ to execute scripts and commands at startup. We add a line to the file to execute the script so that every time the system is started, the script will be executed.
But we first need to add execution permissions to /etc/rc.local,
$ sudo chmod x /etc/rc.local
Then add the script to be executed:
$ sudo vi /etc/rc.local
Add at the end of the file:
sh /root/script.sh &
Then save the file and exit. The same goes for using the rc.local file to execute commands, but be sure to fill in the full path of the command. To know the full path of the command, run:
$ which command
for example:
$ which shutter
/usr/bin/shutter
If it is CentOS, we modify the file /etc/rc.d/rc.local instead of /etc/rc.local. But we also need to add executable permissions to the file first.
Note: - The script executed at startup must end with exit 0.
This method is the simplest. We create a cron job that waits 90 seconds after system startup and then executes commands and scripts.
To create a cron task, open a terminal and execute
$ crontab -e
Then enter the following content,
@reboot ( sleep 90 ; sh \location\script.sh )
Here \location\script.sh is the address of the script to be executed.
The above is the detailed content of Teach you how to write execution commands/scripts when Linux starts or restarts. For more information, please follow other related articles on the PHP Chinese website!