Start a programm automatically at the start of a Linux System (Debian and Ubuntu)
To start a program at the beginning of a Debian operating system session, you have several options depending on your needs and the specific type of program you want to start. Here are some common methods:
### Method 1: Using `rc.local`
The `/etc/rc.local` script runs at the end of each multiuser runlevel. You can add your program to this script to have it start on boot.
1. Open `/etc/rc.local` with a text editor, e.g., nano:
„`sh
sudo nano /etc/rc.local
„`
2. Add your command before the `exit 0` line:
„`sh
/path/to/your/program &
„`
3. Save and exit the editor.
4. Make sure `/etc/rc.local` is executable:
„`sh
sudo chmod +x /etc/rc.local
„`
### Method 2: Using Systemd
Systemd is the init system used by Debian to manage system services. You can create a service file to manage your program.
1. Create a new service file in `/etc/systemd/system`, e.g., `myprogram.service`:
„`sh
sudo nano /etc/systemd/system/myprogram.service
„`
2. Add the following content to the file, adjusting it to match your program:
„`ini
[Unit]
Description=My Program Service
After=network.target
[Service]
ExecStart=/path/to/your/program
Restart=always
[Install]
WantedBy=multi-user.target
„`
3. Reload the systemd manager configuration:
„`sh
sudo systemctl daemon-reload
„`
4. Enable the service to start at boot:
„`sh
sudo systemctl enable myprogram.service
„`
5. Start the service immediately:
„`sh
sudo systemctl start myprogram.service
„`
### Method 3: Using Cron
Cron can be used to schedule tasks, including running a program at boot time.
1. Open the crontab editor for the root user:
„`sh
sudo crontab -e
„`
2. Add the following line to the crontab file:
„`sh
@reboot /path/to/your/program
„`
3. Save and exit the editor.
### Method 4: Using `.xsessionrc` (for GUI Programs)
If you want to start a program when a specific user logs in to a graphical environment, you can use the `.xsessionrc` file.
1. Edit the `.xsessionrc` file in the user’s home directory:
„`sh
nano ~/.xsessionrc
„`
2. Add your command:
„`sh
/path/to/your/program &
„`
3. Save and exit the editor.
### Method 5: Using Desktop Environment Autostart (for GUI Programs)
Most desktop environments like GNOME, KDE, XFCE have their own way to autostart applications.
1. Create a `.desktop` file in `~/.config/autostart`:
„`sh
mkdir -p ~/.config/autostart
nano ~/.config/autostart/myprogram.desktop
„`
2. Add the following content to the file:
„`ini
[Desktop Entry]
Type=Application
Exec=/path/to/your/program
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
Name=My Program
„`
3. Save and exit the editor.
### Conclusion
Choose the method that best suits your needs. For system services and background programs, using `rc.local` or Systemd is typically the best approach. For user-specific or graphical programs, using `.xsessionrc` or the desktop environment’s autostart functionality is more appropriate.