Domanda

I'm writing a bash script meant to run on a remote AMP stack. The script needs to access a PHP predefined environment variable ($_ENV).

This is what I want:

db_host=$(php -r 'echo $_ENV{DATABASE_SERVER};')
echo "The DB Host is: $db_host"
# output: "The DB Host is: internal-db.s173785.gridserver.com"

This is what I get instead:

# METHOD 1
db_host1=$(php -r 'echo $_ENV{DATABASE_SERVER};')
echo "The DB Host is: $db_host1"
# output: "The DB Host is: "

# METHOD 2
db_host2=`php -r 'echo get_env(DATABASE_SERVER);'`
echo "The DB Host is: $db_host2"
# output: "The DB Host is: "

Neither method works, both variables return empty. I know that this PHP variable is set, because when I type this into the terminal (after ssh'ing into the server), I get the expected value:

$ php -r 'echo $_ENV{DATABASE_SERVER};' 
# outputs: "internal-db.s173785.gridserver.com"

Technically the above methods should work, because I managed to get this working in my script:

php_user=$(php -r 'echo getenv("USER");')
echo php_user is $php_user
# outputs: "php_user is myusername"

Anyone know what I am doing wrong?\

***UPDATE*******

I should mention that I am invoking this script from my local machine like so:

ssh -t user@mydomain.com "myscript backup_remote_db"

"myscript" is the name of my executable bash script, and "backup_remote_db" is the function I'm passing to it which contains the code above.

This might not be cause however, because when I echo $USER in the script, it echoes the remote user, not the local one...

***UPDATE 2******

Here is how I finally got it working:

db_host=$DATABASE_SERVER
echo "The DB Host is $db_host"
# output: "The DB Host is: internal-db.s173785.gridserver.com"

But only if I make this adjustment to how the script is invoked:

ssh -t user@mydomain.com ". /etc/profile; myscript backup_remote_db"
È stato utile?

Soluzione

You don't need php for get environment variables in your shell

Just print it:

 echo "The DB Host is $DATABASE_SERVER"

And for full answer, I assume, that php doesn't work because you get notice Use of undefined constant PATH, you should wrap your string arguments.
This should work:

v=$(php -r 'print_r(getenv("DATABASE_SERVER"));')
echo "DB: $v"

Update: .bashrc is not sourced when you log in using SSH. You need to source it in your .bash_profile like this:

if [ -f ~/.bashrc ]; then
  . ~/.bashrc
fi
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top