Cant execute script as root

My preferred approach is to use systemd

If the service is run as root I have a folder

/etc/systemd/scripts

Then I create a systemd service in

/etc/systemd/system/<myservice.service>

If the service is to be run at specific intervals I create a timer

/etc/systemd/system/<myservice.timer>

Then I enable and start the timer

systemctl enable --now <myservice.timer>

For a practical implementation of a user script/service/timer construct - you could look at [root tip] [Utility Script] Charger Notifier - battery state

Once you understand the concept it would be fairly easy to adapt to a systemwide service.

practical appliance

See-> systemd/Timers - ArchWiki

Switch to root context

su -l root

Create a folder to hold your script (executed by service)

mkdir -p /etc/systemd/scripts

Copy your script to the folder

cp btrfs-to-sda-backup.sh /etc/systemd/scripts

Switch to /etc/systemd/system folder

cd /etc/systemd/system

Create a service file

cat << EOF > /etc/systemd/system/btrfs-to-sda-backup.service
[Unit]
Description=Backup to SDA

[Service]
Type=oneshot
ExecStart=/etc/systemd/scripts/btrfs-to-sda-backup.service

[Install]
WantedBy=multi-user.target
EOF

Create the timer

cat << EOF > /etc/systemd/system/btrfs-to-sda-backup.timer
[Unit]
Description=Backup to SDA

[Timer]
OnBootSec=3h
OnUnitActiveSec=3h

[Install]
WantedBy=timers.target
EOF

Activate the timer

systemctl enable --now system/btrfs-to-sda-backup.timer
3 Likes