0

I have a bash script. This script can be started as part of a systemd service (or transient systemd task with systemd-run). One can also run it stand alone.

How can I see if “the current script” is being run as part of a systemd service?

I can see if the systemd service is running with if systemctl -q is-active my_service_name.service ; then …, but that will always be true inside the service. I want to detect if the script is not being run as part of that systemd service.

This is run on Ubuntu Linux 18.04, 20.04 & 22.04, so whatever versions of systemd & bash are installed via apt on them.

Amandasaurus
  • 30,211
  • 62
  • 184
  • 246
  • 1
    You can check the parent process. Variable `PPID` may help – Romeo Ninov Jun 29 '22 at 09:01
  • There are lots of other enviromental things that are easy to detect. perhaps one of them would be easier? – Jasen Jun 29 '22 at 09:52
  • 1
    I assume `run stand alone` means it is invoked interactively from a command line. In that case this should answer the question: https://unix.stackexchange.com/questions/46789/check-if-script-is-started-by-cron-rather-than-invoked-manually/46801#46801 – Gerald Schneider Jun 29 '22 at 10:12
  • You can add a check for systemd namespace or cgroup – kofemann Jul 04 '22 at 12:01

0 Answers0