2

Is there any way to execute a file.py if a file.config has a recent modified date? Like execute a script if some file is modified?

Thanks in advance!

1

1 Answer 1

5

This can be done with systemd's path units:

# /etc/systemd/system/file.path
[Unit]
Description=Watches file.config for changes

[Path]
PathChanged=/path/to/file.config

[Install]
WantedBy=multi-user.target

That will watch file.config and trigger file.service whenever that file changes. file.service can run your python script:

#/etc/systemd/system/file.service
[Unit]
Description=Does something after changing file.config

[Service]
Type=oneshot
ExecStart=/usr/bin/python3 /path/to/file.py

Test it with systemctl start file.path. Then touch /path/to/file.config. You should see file.py fire.

You can also watch directories. If new files are added to a directory, you can trigger the path and process these files.


Did a little test on my own system to verify it works:

stew@laptop:~/.config/systemd/user$ cat file.{path,service}
[Path]
PathChanged=%h/file
[Service]
Type=oneshot
ExecStart=/bin/bash -c 'echo I did something'

$ systemctl --user start file.path
$ touch ~/file
$ systemctl --user status file.service
● file.service
     Loaded: loaded (/home/stew/.config/systemd/user/file.service; static)
     Active: inactive (dead) since Fri 2022-08-05 16:29:44 CEST; 1s ago
TriggeredBy: ● file.path
    Process: 296588 ExecStart=/bin/bash -c echo I did something (code=exited, status=0/SUCCESS)
   Main PID: 296588 (code=exited, status=0/SUCCESS)
        CPU: 2ms

Aug 05 16:29:44 SIM-5532-007 systemd[1746]: Starting file.service...
Aug 05 16:29:44 SIM-5532-007 bash[296588]: I did something
Aug 05 16:29:44 SIM-5532-007 systemd[1746]: file.service: Succeeded.
Aug 05 16:29:44 SIM-5532-007 systemd[1746]: Finished file.service.
$ touch ~/file
$ touch ~/file
$ journalctl --user -u file.service -f
-- Journal begins at Mon 2022-05-30 10:11:55 CEST. --
Aug 05 16:29:44 SIM-5532-007 systemd[1746]: Starting file.service...
Aug 05 16:29:44 SIM-5532-007 bash[296588]: I did something
Aug 05 16:29:44 SIM-5532-007 systemd[1746]: file.service: Succeeded.
Aug 05 16:29:44 SIM-5532-007 systemd[1746]: Finished file.service.
Aug 05 16:29:50 SIM-5532-007 systemd[1746]: Starting file.service...
Aug 05 16:29:50 SIM-5532-007 bash[296594]: I did something
Aug 05 16:29:50 SIM-5532-007 systemd[1746]: file.service: Succeeded.
Aug 05 16:29:50 SIM-5532-007 systemd[1746]: Finished file.service.
Aug 05 16:30:10 SIM-5532-007 systemd[1746]: Starting file.service...
Aug 05 16:30:10 SIM-5532-007 bash[296621]: I did something
Aug 05 16:30:10 SIM-5532-007 systemd[1746]: file.service: Succeeded.
Aug 05 16:30:10 SIM-5532-007 systemd[1746]: Finished file.service.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.