Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating filename_$(date %Y-%m-%d) from systemd bash inline script

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.

like image 584
bobbytables Avatar asked Sep 01 '17 11:09

bobbytables


People also ask

How do I put the date in a FileName?

I'd use YYYY-MM-DD HHmmss for filenames, unless there is a particular need for timezones or a possible need to parse them into ISO dates; in those cases an ISO date would probably be preferrable.

What does %% mean in bash?

So as far as I can tell, %% doesn't have any special meaning in a bash function name. It would be just like using XX instead. This is despite the definition of a name in the manpage: name A word consisting only of alphanumeric characters and under- scores, and beginning with an alphabetic character or an under- score.

How do I append to a file in bash?

How to append to file in Bash. To make a new file in Bash, you normally use > for redirection, but to append to an existing file, you would use >> .


1 Answers

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

As described here:

  • https://github.com/systemd/systemd/issues/2146
  • https://www.freedesktop.org/software/systemd/man/systemd.service.html#Command%20lines

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'
like image 196
cptPH Avatar answered Nov 15 '22 16:11

cptPH