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?

Roger
  • 8,286
  • 17
  • 59
  • 77
  • 2
    Please do not edit answers to add your question in it. Instead edit edit your own question and comment on the answer. – Lekensteyn Jun 03 '11 at 20:31

7 Answers7

10
php_cwd=`/usr/bin/php << 'EOF'
<?php echo getcwd(); ?>
EOF`
echo "$php_cwd" # Or do something else with it
phihag
  • 278,196
  • 72
  • 453
  • 469
8
PHP_OUT=`php -r 'echo phpinfo();'`
echo $PHP_OUT;
David Chan
  • 7,347
  • 1
  • 28
  • 49
3

Alternatively:

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

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

EDIT: ninja'd by David Chan.

damianb
  • 1,224
  • 7
  • 16
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
evandrix
  • 6,041
  • 4
  • 27
  • 38
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
-1

This is what worked for me:

VAR='/$#'
php_cwd=`/usr/bin/php << EOF
<?php echo preg_quote("$VAR"); ?>
EOF`
echo "$php_cwd"
Roger
  • 8,286
  • 17
  • 59
  • 77
-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.

Kar.ma
  • 743
  • 6
  • 12
koressak
  • 191
  • 2
  • 10
  • 4
    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. – netcoder Jun 03 '11 at 20:05
  • 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?? – koressak Jun 03 '11 at 20:11
  • I used the php's getcwd() function only to illustrate the bash operation. It's just a cummon example to make the question simpler. – Roger Jun 03 '11 at 20:12
  • 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. – koressak Jun 03 '11 at 20:14
  • I am the one who has to apologize. – Roger Jun 03 '11 at 20:17