Search code examples
linuxbashsystemd

Bash: Date-epoch with systemd


I execute the following line in a bash console.

/bin/bash -c "echo `date` random=$((RANDOM % 10)) > /tmp/my.log"

The content of my.log is as expected.

Mo Aug 24 14:37:04 CEST 2020 random=6

Now I change the timestamp to epoch (format-code +%s).

/bin/bash -c "echo `date +%s` random=$((RANDOM % 10)) > /tmp/my.log"

File is

1598272710 random=3

As expected again.

But if I put this command line into systemd it would fail.

[Service]                                                                                                             
ExecStart=/bin/bash -c "echo `date +%s` random=$((RANDOM % 10)) > /tmp/my.log"  

produces

/bin/sh random=7

Must be a problem with the format-code of date. If I remove the +%s then it is as expected (normal date-format and no epoch) with systemd too.

Any suggestions what is wrong with my command? Thanks!


Solution

  • The %-secuences are replaced by systemd. From systemd.unit manual:

    Specifiers

    "%s" User shell This is the shell of the user running the service manager instance. In case of the system manager this resolves to "/bin/sh".

    %s is substituted for /bin/sh, and date +/bin/sh returns /bin/sh.

    Do:

    ExecStart=/bin/bash -c "echo $(date +%%s) random=$((RANDOM %% 10)) > /tmp/my.log"
    

    Using backticks ` is discouraged. Use $(...) instead. bash hackers wiki deprecated and obsolete syntax