0

I'm trying to evaluate dateFrom variable inside dateCalc variable that evaluate PHP command.

dateFrom="2013-01-05"
dateCalc=$(php -r '$date = new DateTime($dateFrom);echo $date->add(DateInterval::createFromDateString("-2 days"))->format("Y-m-d");')

In the actual script, the date will be dynamic var.

Is there a way I can evaluate the dateFrom inside the PHP command? if it's not possible, is there a way I can achieve the same result of the PHP command in another way? other shell commands?

1 Answers1

1

In general, it's best to pass the variable through the environment or as a command line argument:

$ export myvar=foobar
$ php -r 'printf("envvar is \"%s\"\n", getenv("myvar"));'
envvar is "foobar"

or

$ myvar=foobar php -r 'printf("envvar is \"%s\"\n", getenv("myvar"));'
envvar is "foobar"

or

$ php -r 'printf("arg is \"%s\"\n", $argv[1]);' foobar
arg is "foobar"

While you could embed the variable data in the PHP script itself, it would be a bad idea as anything the value would be confused with PHP syntax, unless you too really good care to make sure the value was quoted properly.


That said, if all you want is to get the date two days before, just using GNU date would do:

$ date -d '2013-01-05 - 2 days' +%F
2013-01-03

Or n days before any arbitrary YYYY-MM-DD formatted date stored in a variable:

$ dateFrom=2013-01-05 n=7
$ date -d "$dateFrom - $n days" +%F
2012-12-29
ilkkachu
  • 138,973