Creating a custom watcher script

Hey there good people of NixOS community!

I am a complete newbie and will probably get shunned but I have been trying to get at this issue for quite a while now and seem to be just stuck :frowning:

I am trying to create a systemd service with a simple script that will copy the /etc/nixos/configuration.nix file whenever that file changes. The file will be copied into a specific git filder and then commited and pushed.

I already have a script that fullfils the core functionality:

#!/bin/sh

SCRIPT_DIR="$(dirname "$0")"

# Copy configuration.nix to the script's directory
sudo cp /etc/nixos/configuration.nix "$SCRIPT_DIR/"

# Change to the script's directory for git operations
cd "$SCRIPT_DIR" || exit 1

# Update permissions and ownership
sudo chmod 666 ./configuration.nix && \
sudo chown $USER:users ./configuration.nix

# Git operations
git add --all && \
git commit -m "Update configuration.nix" && \
git push

The problem I am having is firstly; how can i get the service to setup properly in the and secondly; how to make it run whenever the /etc/nixos/configuration.nix gets changed.

Thank you in advance,
Simon

It’s pretty common to have a git repo /etc/nixos. I only mention it because the question comes up from time to time.

The usual way to write a watcher script would be with inotify tools like inotifywait.

NixOS also let’s you run scripts during system activation (when you run nixos-rebuild) with the system.activationScripts option.

Use systemd.services.<name>.* options, there are many examples of using it in the nixpkgs repo, where <name> is whatever you want to call the service. Don’t use sudo in your script, just run the service as root, and make sure the necessary binaries are in the service’s path. There are systemd.services.<name>.script and systemd.services.<name>.path that may make this easier for you.

You would also create a systemd.paths.<name> unit to monitor the applicable paths. (This uses inotify underneath.)

Activation scripts are best avoided, because an error in such a script or an incorrectly written script can prevent you from booting. It’s also just not necessary for this use case.

For watching a folder for file changes you could use entr