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
Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
ilkkachu
  • 133,243
  • 15
  • 236
  • 397
  • Thank you, I still need to use var inside var, how can I do it? `dateFrom="2013-01-05" dateCalc=$(date -d '${dateFrom} - 2 days' +%F) echo $dateCalc` – user531769 Jun 28 '22 at 17:22
  • I need to calculate 7 days ago from a specific date and do it again on the result. – user531769 Jun 28 '22 at 17:23
  • @user531769, see edit – Stéphane Chazelas Jun 28 '22 at 18:11
  • @StéphaneChazelas, your example is not good because in my case I need the variable to be inside a command expression - backtick or $() – user531769 Jun 28 '22 at 19:17
  • @user531769, and? – Stéphane Chazelas Jun 28 '22 at 19:24
  • @user531769, if the command there gives the output you want, then you can store it in a variable by wrapping that same command in `$(...)`, and assigning to a variable. `var=$(date -d "$dateFrom - $n days" +%F)`. Don't change the double quotes to single quotes, it'll prevent that variable from being expanded. See: [What is the difference between the "...", '...', $'...', and $"..." quotes in the shell?](https://unix.stackexchange.com/questions/503013/what-is-the-difference-between-the-and-quotes-in-th) – ilkkachu Jun 28 '22 at 19:59
  • @StéphaneChazelas,@ilkkachu you are so right, I did try it yesterday and it didn't work but maybe I was tired because now it's working. many thanks! – user531769 Jun 29 '22 at 08:55