3

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 ?

1
  • Why don't you just make it in PHP and call the php? php test.php can also be called on command line same way you do with a bash script. Seems you're also more comfortable with PHP anyway. Commented Mar 3, 2014 at 6:45

2 Answers 2

4

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']")
Sign up to request clarification or add additional context in comments.

Comments

3

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 =.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.