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
-
Create the Script: Ensure your script exists and is executable. For example, create
/data/om/set_fan_speed.shwith the necessary commands.Make it executable:
sudo chmod +x /data/om/set_fan_speed.shExample script content:
#!/bin/bash # Your commands here echo "Setting fan speed..." > /tmp/fan_log.txt -
Create the Service File: Create a new service file in
/etc/systemd/system/.sudo nano /etc/systemd/system/set_fan_speed.serviceAdd 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.
-
Reload systemd: After creating or editing the service file, reload the daemon.
sudo systemctl daemon-reload -
Enable the Service: Enable it to start on boot.
sudo systemctl enable set_fan_speed.service -
Test the Service: Start it manually to verify it works.
sudo systemctl start set_fan_speed.service sudo systemctl status set_fan_speed.serviceCheck 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 usesystemctl --usercommands. - Alternatives:
- Use cron with
@rebootincrontab -e. - Add to
/etc/rc.local(deprecated in newer Ubuntu versions).
- Use cron with
- Troubleshooting: If the service fails, check the script’s output and ensure all paths are absolute. Use
systemctl statusandjournalctlfor debugging. - Security: Avoid running unnecessary scripts as root; use the least privilege principle.