0

I want to know the time duration since a systemd service was started, using the --property=ActiveEnterTimestamp i can see the time it has started, and i would like to compare it with current time and get a value in seconds or minutes, how can i achieve this with bash

If i use this solution i am getting a string, but i cannot actually get any time object to make the decision, any help on this would be appreciated.

windowws
  • 373
  • 1
  • 8
  • 20
  • 2
    Note that bash doesn't work with "objects" of any sort. It has some support for arithmetic if you can transform things to numbers, but most of the time it's just passing strings to and from other commands. Generally, people asking "how can I do this with bash?" should really be asking "what standard utility program can I use to do this?" – IMSoP Apr 25 '22 at 12:03
  • top -b -n 1 | grep systemd. It should be a good start, then you can parse the output to get the time. It's only part of the answer, I don't have much time to do a proper and complete one. I'm not sure if it's the good answer too. – LittlePanic404 Apr 25 '22 at 12:09
  • @LittlePanic404, that's measuring systemd itself, not a service it started. Also, systemd services are organized into cgroups, so there are a lot of extra OS-level facilities for cgroup-level accounting that `top` doesn't understand. – Charles Duffy Apr 25 '22 at 16:34
  • @CharlesDuffy thanks for your insight, I'm not expert at all in this domain :) – LittlePanic404 Apr 26 '22 at 07:50

1 Answers1

1

You could use GNU date to convert the ActiveEnterTimestamp value to seconds-since-the-epoch, then subtract the current seconds-since-the-epoch to get the running time in seconds.

servicestartsec=$(date -d "$(systemctl show --property=ActiveEnterTimestamp your-service-here | cut -d= -f2)" +%s)
serviceelapsedsec=$(( $(date +%s) - servicestartsec))

Substitute "your-service-here" for your actual service name.

The first line assigns the start time in seconds by extracting the date portion of systemctl show --property=ActiveEnterTimestamp... (using cut to extract the second =-delimited field) and then passing it to GNU date and asking for output in seconds-since-the-epoch.

The second line simply subtracts that start time from the current time to get an elapsed time in seconds. Divide that as needed to get elapsed minutes, hours, etc.

Jeff Schaller
  • 2,352
  • 5
  • 23
  • 38