Search code examples
bashlaunchdlaunch-agent

Include current date as program argument in LaunchAgents


Suppose I want to do something with a file that contains the current date. At a bash prompt I could just do this:

$ touch /Foo/$(date +%Y-%m-%d)

How could I do that in a LaunchAgents plist, where I don't have $() available?

<key>ProgramArguments</key>
<array>
  <string>touch</string>
  <string>/Foo/CURRENT-DATE-HERE</string>
</array>

Solution

  • One possibility is to have it launch a shell to do the expansion and then run the real command:

    <key>ProgramArguments</key>
    <array>
      <string>bash</string>
      <string>-c</string>
      <string>touch /Foo/$(date +%Y-%m-%d)</string>
    </array>
    

    Note that the entire command is passed to bash as a single argument, and then it splits into the command vs argument(s) due to the embedded space. If it's a long-running command, you might want to use exec touch /Foo/$(date +%Y-%m-%d) so that the shell will replace itself with the command rather than running the command as a subprocess, then hanging out waiting for it to exit.