Question

I need parse uri in shell scripts. So, I tried to use php in bash as below.

#!/bin/sh

uri="http://www.google.com?key=value
key="host"

value=$(php -r "$parse = parse_url('$uri'); echo $parse['$key']")

It has showing the following error.

PHP Parse error:  syntax error, unexpected '=' in Command line code on line 1

Some body can help how to use embedded php in bash ?

No correct solution

OTHER TIPS

A cheap way of debugging this is to use echo to see what you're passing in to php:

echo "$parse = parse_url('$uri'); echo $parse['$key']"

shows

 = parse_url('http://www.google.com?key=value'); echo ['host']

You're already using $uri to mean "the value of the shell variable uri", so it's not surprising that $parse is also considered a shell variable and expanded to its value (unset, nothing).

Use \$ when you want a literal dollar sign in your double quoted string:

value=$(php -r "\$parse = parse_url('$uri'); echo \$parse['$key']")

You can use it easily, but you must be careful because of escaping in bash.

I recommend to use single quotes (you do not need to escape anything) and exit from the quotes when you want to do something special. Your example:

php -r '$parse=parse_url("'$url'"); echo $parse["'$part'"];'

Note that

  • you do not need to escapes $parse
  • you need to exit from single quotes when inserting bash variable: '$url'
  • you cannot use single quotes in the single quotes! do use double quotes " instead.

Update:

Just for the clarification - parse error happened because $parse was interpreted as bash variable (empty string) so the php command incorrectly started with =.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top