Roger
Roger

Reputation: 8586

How to pass a variable to a php function inside a Bash Script

How can I pass a variable to a php function inside a Bash Script? For example:

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

This is another attempt:

VAR='VARIABLE'
php_var=`php -r 'echo $VAR;'`
echo $php_var

Resulting:

PHP Notice:  Undefined variable: VAR in Command line code on line 1
Notice: Undefined variable: VAR in Command line code on line 1

Upvotes: 1

Views: 962

Answers (2)

amit_g
amit_g

Reputation: 31270

Enclose the variable in quote to make it static string for php

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

Upvotes: 1

Adam Wright
Adam Wright

Reputation: 49386

If you want to access environment variables, you can use getenv. Similarly, putenv will add variables to the environment. However, bash should perform normal variable expansion inside the heredoc, so what you've pasted should work reasonably, if the contents are useful as a static string (in your case, you'll need to quote the usage, or add quotes to your environment variable).

Unfortunately, it will also try and substitute out normal PHP variable usage, as it has the same syntax. You'll need to escape the $ in any normal PHP variable names to avoid this.

Upvotes: 1

Related Questions