9

I am trying to run a PHP function inside Bash... but it is not working.

#! /bin/bash

/usr/bin/php << 'EOF'
<?php echo getcwd(); ?>
EOF

In the reality, I needed to keep the return value in a bash variable... By the way, I am using the php's getcwd() function only to illustrate the bash operation.

UPDATE: Is there a way to pass a variable?

VAR='/$#'
php_cwd=`/usr/bin/php << 'EOF'
<?php echo preg_quote($VAR); ?>
EOF`
echo "$php_cwd"

Any ideas?

1
  • 2
    Please do not edit answers to add your question in it. Instead edit edit your own question and comment on the answer. Commented Jun 3, 2011 at 20:31

7 Answers 7

10
php_cwd=`/usr/bin/php << 'EOF'
<?php echo getcwd(); ?>
EOF`
echo "$php_cwd" # Or do something else with it
Sign up to request clarification or add additional context in comments.

Comments

8
PHP_OUT=`php -r 'echo phpinfo();'`
echo $PHP_OUT;

Comments

3

Alternatively:

php_cwd = `php -r 'echo getcwd();'`

replace the getcwd(); call with your php code as necessary.

EDIT: ninja'd by David Chan.

Comments

1

This is how you can inline PHP commands within the shell i.e. *sh:

#!/bin/bash

export VAR="variable_value"
php_out=$(php << 'EOF'
<?
    echo getenv("VAR"); //input
?>
EOF)
>&2 echo "php_out: $php_out"; #output

Comments

1

Use '-R' of php command line. It has a build-in variable that reads inputs.

VAR='/$#'
php_cwd=$(echo $VAR | php -R 'echo preg_quote($argn);')
echo $php_cwd

Comments

-1

This is what worked for me:

VAR='/$#'
php_cwd=`/usr/bin/php << EOF
<?php echo preg_quote("$VAR"); ?>
EOF`
echo "$php_cwd"

Comments

-2

I have a question - why don't you use functions to print current working directory in bash? Like:

#!/bin/bash
pwd # prints current working directory.

Or

#!/bin/bash
variable=`pwd`
echo $variable

Edited: Code above changed to be working without problems.

5 Comments

That really doesn't answer OP's question. The code also does not produce OP's expected output. Lastly, questions should be comments, not answers.
Well, it was rhetorical question to be honest. Well, I have mistyped the second part of the code and going to edit it now to the point it will work. For the first part of your comment - yes, it does not answer the question absolutely strictly the same way it poster wants to, but - if he/she wants to save it as a bash variable, why use php??
I used the php's getcwd() function only to illustrate the bash operation. It's just a cummon example to make the question simpler.
Oh, for that I'm sorry @netcoder, @Roger. It seemed to me little strange to use php in bash, so I thought you were looking for a way to get the path.
I am the one who has to apologize.

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.