12

I am trying to execute a systemd timer and would like to keep the output from the executed script in a file per date. Here is my ExecStart script in the .service file:

ExecStart=/bin/bash -c 'echo $(date +%Y-%m-%d) >> /home/username/test_output_$(date +%Y-%m-%d).log'

This creates the file but adds a "hash" instead of the month name:

~/test_output_2017-ea3c0c2dd56c499a93412641e41008db-01.log

The content is the same:

2017-ea3c0c2dd56c499a93412641e41008db-01

If I run /bin/bash -c 'echo $(date +%Y-%m-%d)' in the shell without passing it through systemd service, it works as expected. Prints: 2017-09-01.

Does %m stand for something else than a month number in the systemd environment?

Any idea how to set the systemd service to put the standard output from the script into a file with the current date? Expected result: test_output_2017-09-01.log

Thank you.

bobbytables
  • 303
  • 1
  • 2
  • 7
  • 2
    did you tried `\`date +%Y-%m-%d`\` instead of `$(date +%Y-%m-%d)` ? – twooBeers Sep 01 '17 at 11:53
  • 2
    `$(...)` evaluates the command. Otherwise, if we omit it, it will print `date +%Y-%m-%d` as a string and nothing more. – bobbytables Sep 01 '17 at 12:53
  • 1
    ` ... ` its like $(...) .. called command substitution => https://www.gnu.org/software/bash/manual/html_node/Command-Substitution.html#Command-Substitution – twooBeers Sep 04 '17 at 08:19
  • Possible duplicate of [Append date to filename in linux](https://stackoverflow.com/q/1795678/608639), [Appending a current date from a variable to a filename](https://unix.stackexchange.com/q/57590), [Adding timestamp to a filename with mv in BASH](https://stackoverflow.com/q/8228047/608639), etc. – jww Oct 15 '19 at 08:24

1 Answers1

14

You'll need to escape the $ and % signs, by doubling them both in order to make this work.

As described here:

To pass a literal dollar sign, use "$$"

ExecStart=/bin/bash -c 'echo $$(date +%%Y-%%m-%%d) >> /home/username/test_output_$$(date +%%Y-%%m-%%d).log'
cptPH
  • 2,401
  • 1
  • 29
  • 35