Run a Script on Startup in Ubuntu (Systemd)

Overview

To run a script automatically on system startup in Ubuntu, use systemd service units. This method is reliable and integrates well with the system’s init process.

Steps

  1. Create the Script: Ensure your script exists and is executable. For example, create /data/om/set_fan_speed.sh with the necessary commands.

    Make it executable:

    sudo chmod +x /data/om/set_fan_speed.sh
    

    Example script content:

    #!/bin/bash
    # Your commands here
    echo "Setting fan speed..." > /tmp/fan_log.txt
    
  2. Create the Service File: Create a new service file in /etc/systemd/system/.

    sudo nano /etc/systemd/system/set_fan_speed.service
    

    Add the following content:

    [Unit]
    Description=Set fan speed on startup
    After=network.target  # Optional: Run after network is up
    
    [Service]
    Type=oneshot  # For scripts that run once and exit
    ExecStart=/data/om/set_fan_speed.sh
    RemainAfterExit=yes  # Keeps the service as active after script finishes
    
    [Install]
    WantedBy=multi-user.target
    
    • Type=oneshot: Suitable for scripts that run and exit.
    • RemainAfterExit=yes: Ensures the service is considered active after the script completes.
    • Adjust paths and dependencies as needed.
  3. Reload systemd: After creating or editing the service file, reload the daemon.

    sudo systemctl daemon-reload
    
  4. Enable the Service: Enable it to start on boot.

    sudo systemctl enable set_fan_speed.service
    
  5. Test the Service: Start it manually to verify it works.

    sudo systemctl start set_fan_speed.service
    sudo systemctl status set_fan_speed.service
    

    Check logs if needed:

    sudo journalctl -u set_fan_speed.service
    

Important Notes

  • Permissions: The script must be executable. If it requires root privileges, ensure the service runs as root (default) or specify a user with User= in the [Service] section.
  • User Services: For user-specific scripts (not system-wide), place the service in ~/.config/systemd/user/ and use systemctl --user commands.
  • Alternatives:
    • Use cron with @reboot in crontab -e.
    • Add to /etc/rc.local (deprecated in newer Ubuntu versions).
  • Troubleshooting: If the service fails, check the script’s output and ensure all paths are absolute. Use systemctl status and journalctl for debugging.
  • Security: Avoid running unnecessary scripts as root; use the least privilege principle.

References