In this tutorial, we will explain how to execute script or command on reboot or startup in Linux. There was a requirement on one of our project to run the script on startup or reboot where script run in a loop until you forcefully kill that script.
These methods you can use in CentOS/RHEL and Ubuntu machine which will execute a command or scripts at every reboot or at startup.
Method 1: You can schedule this script in Crontab
This is one of the easiest methods. So create the Cron job that will execute at startup.
Steps to create Cron Job:
$ crontab –e ##Add your script here…. @reboot /your-script-location/script-name.sh
“/your-script-location/script-name.sh” enter the full path of your script which you want to execute.
Method 2 – Add your script in a rc.local file.
In this method, we will show you how to add the script to a rc.local file.
- Edit file “/etc/rc.d/rc.local”
- Add your script or command at the end of the file which you want to execute
Every time whenever your machine rebooted your script/command which you have done an entry in the rc.local file will get executed.
Note: Provide required permission to execute your script and also “/etc/rc.d/rc.local”
$ sudo chmod +x /etc/rc.d/rc.local
Add script in rc.local file
$ sudo vi /etc/rc.d/rc.local /bin/sh /your-script-path/script-name.sh & Esc + :wq
Note: Make sure that the script ends with ‘exit 0’
Save and exit the file. Similar to this you can add command with the full path of the command.
Steps to check the full path of any command
$ which command-name
For example,
$ which locate /usr/bin/locate
For Amazon Linux or CentOS, we use file ‘/etc/rc.d/rc.local’ instead of ‘/etc/rc.local’. We also need to make this file executable.
Method 3: Executing Linux Scripts at Logout and Login
This method is used to execute the script at ssh-user Login or Logout, Just you need to add your line at end of the file in “~.bash_profile” and “~.bash_logout”
In this article, we explained how to execute script or command on reboot or startup in Linux and also to execute a script when a user Login and Logout on a Linux machine.
Read Other Articles
Steps to connect Linux Server from windows using Putty
Basic Linux Storage and Scenario