Linux

How to execute script or command on reboot or startup in Linux

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.

Methods 1: You can schedule this script in Crontab

This is one of the easiest methods. So create the Cron job what will execute at startup.

Steps to create Cron Job:

“/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.How to execute script or command on reboot or startup in Linux

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”

Add script in rc.local file

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

For example,

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.

Related Articles

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Close

Adblock Detected

Please consider supporting us by disabling your ad blocker