Roger
Roger

Reputation: 8576

Run PHP function inside Bash (and keep the return in a bash variable)

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?

Upvotes: 9

Views: 10301

Answers (7)

koressak
koressak

Reputation: 191

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.

Upvotes: -2

Shouguang Cao
Shouguang Cao

Reputation: 9

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

Upvotes: 1

evandrix
evandrix

Reputation: 6210

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

Upvotes: 1

Roger
Roger

Reputation: 8576

This is what worked for me:

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

Upvotes: -1

damianb
damianb

Reputation: 1224

Alternatively:

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

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

EDIT: ninja'd by David Chan.

Upvotes: 3

David Chan
David Chan

Reputation: 7505

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

Upvotes: 8

phihag
phihag

Reputation: 288090

php_cwd=`/usr/bin/php << 'EOF'
<?php echo getcwd(); ?>
EOF`
echo "$php_cwd" # Or do something else with it

Upvotes: 10

Related Questions