1

I have access to an Ubuntu server with PHP 7.0. I can run the following code without any problems:

php -r "echo 'hello world';"

But when I add an assignment operator like this:

php -r "echo 'hello world'; $t = 'hello world';"

I get the following error:

PHP Parse error: syntax error, unexpected '=', expecting end of file in Command line code

I just realized while typing this question that this is probably happening because the shell is trying to evaluate $t. Is there anyway to make it not evaluate $t? The reason I ask is because the code will contain single quotes. I suppose the simple solution would be to change the single quotes in the code to double quotes but if there is a way to do it without altering the code, it might be useful to know.

Cave Johnson
  • 6,499
  • 5
  • 38
  • 57
  • "I just realized while typing this question that this is probably happening because the shell is trying to evaluate $t" - Give that man a cigar! Q: "Is there anyway to make it not evaluate $t?" A: There are SEVERAL ways. For your purposes, just escape the $: `\$t`. – paulsm4 Jan 18 '17 at 01:16

2 Answers2

0
  1. you can use single quotes for php code, but then you can't use them inside php code.
  2. escape all special shell characters in php code with \, ie:

    php -r "echo 'hello world'; \$t = 'hello world';"
    
rsm
  • 2,530
  • 4
  • 26
  • 33
0

To prevent shell variable substitution in your script you should wrap the code in single quotes and use double quotes inside. If you need to have single quotes in your code snippet for whatever reason then escape them with a backslash:

php -r 'echo \'hello world\'; $t = \'hello world\';'
acme
  • 14,654
  • 7
  • 75
  • 109