How to Automatically Run a Command on Reboot in Linux

When managing a Linux server, you often rely on specific background scripts, custom APIs, or database syncing tools that need to be running 24/7. However, if the server unexpectedly reboots due to a power failure or an automated kernel update, those scripts will remain dead until you manually log in via SSH and restart them. To prevent this downtime, you can configure Linux to automatically launch your critical commands the exact moment the system boots up.

Using the ‘@reboot’ Cron Job

While you could write complex Systemd service files, the absolute fastest and simplest way to run a startup script is by leveraging the built-in cron scheduler.

  1. Open your Linux terminal.
  2. Type the following command to edit your user’s crontab file:
    crontab -e
  3. If this is your first time, the terminal will ask you to choose an editor (press 1 for Nano).
  4. Use your arrow keys to scroll all the way to the very bottom of the file, past all the commented lines starting with #.
  5. Type the following syntax:
    @reboot /absolute/path/to/your_script.sh
  6. Save the file by pressing Ctrl + O, hit Enter, and then exit by pressing Ctrl + X.

The terminal will display crontab: installing new crontab. The next time the server turns on, the cron daemon will instantly detect the @reboot flag and execute your script in the background automatically. Always ensure you use absolute paths (like /home/user/script.sh) rather than relative paths, as cron does not load your normal user environment variables.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.

Receive our best articles and tips delivered straight to your inbox.