Assigning values printed by PHP CLI to shell variables - linux

I want the PHP equivalent of the solution given in assigning value to shell variable using a function return value from Python
In my php file, I read some constant values like this:-
$neededConstants = array("BASE_PATH","db_host","db_name","db_user","db_pass");
foreach($neededConstants as $each)
{
print constant($each);
}
And in my shell script I have this code so far:-
function getConfigVals()
{
php $PWD'/developer.php'
//How to collect the constant values here??
#echo "done - "$PWD'/admin_back/developer/developer.php'
}
cd ..
PROJECT_ROOT=$PWD
cd developer
# func1 parameters: a b
getConfigVals
I am able to execute the file through shell correctly.
To read further on what I am trying to do please check Cleanest way to read config settings from PHP file and upload entire project code using shell script
Updates
Corrected configs=getConfigVals replaced with getConfigVals
Solution
As answered by Fritschy, it works with this modification:-
PHP code -
function getConfigVals()
{
php $PWD'/developer.php'
#return $collected
#echo "done - "$PWD'/admin_back/developer/developer.php'
}
shell code -
result=$(getConfigVals)
echo $result

You have to execute the function and assign what is printed to that variable:
configs=$(getConfigVals)
See the manpage of that shell on expansion for more ;)

Related

How to output bash multiline EVAL statement to temp file [duplicate]

This question already has answers here:
How to substitute shell variables in complex text files
(12 answers)
Closed 3 years ago.
Trying to variable replace a templated yaml file.
I'm using eval to take the environment shell variables and replace whats in the file dynamically. I can't figure out how to take the output of this and save to a file.
I just want to take the evaluated output and save to a file.
eval "cat <<EOF
$(<${baseFileName})
EOF"
Exmaple test.yaml
---
value: ${PORT}
Bash environment variable:
PORT=8888
output temp.test.yaml
---
value: 8888
Right now the code will just print the evaluated text to the console.
I've tried.
eval "cat <<EOF
$(<${baseFileName})
EOF" > $newBaseFileName
but no joy. Didn't even create the file.
The reason I'm not using sed is because the file could have unlimited variable decelerations, and I want to replace any value matching a defined bash variable or environment variable. This is part of a template engine. For the life of me I can't remember how I did it before with pure bash.
It didn't work for me but what I did is this
renderTemplate() {
eval "cat <<EOF
$(<${1})
EOF"
}
baseFileName=$(basename $fileName)
templateOutput=`renderTemplate ${baseFileName}`
echo "${templateOutput}"
I'm using this as a temp file anyways so what I'll do is save to variable and then pump that variable in to the command to apply the template as a file. That way it's only ever stored in memory. This is a middleware cli to another cli to add variable replacement to in-memory web hosted files before applying them.
Thanks for your help.

Bash config file or command line parameters

If I am writing a bash script, and I choose to use a config file for parameters. Can I still pass in parameters for it via the command line? I guess I'm asking can I do both on the same command?
The watered down code:
#!/bin/bash
source builder.conf
function xmitBuildFile {
for IP in "{SERVER_LIST[#]}"
do
echo $1#$IP
done
}
xmitBuildFile
builder.conf:
SERVER_LIST=( 192.168.2.119 10.20.205.67 )
$bash> ./builder.sh myname
My expected output should be myname#192.168.2.119 and myname#10.20.205.67, but when I do an $ echo $#, I am getting 0, even when I passed in 'myname' on the command line.
Assuming the "config file" is just a piece of shell sourced into the main script (usually containing definitions of some variables), like this:
. /etc/script.conf
of course you can use the positional parameters anywhere (before or after ". /etc/..."):
echo "$#"
test -n "$1" && ...
you can even define them in the script or in the very same config file:
test $# = 0 && set -- a b c
Yes, you can. Furthemore, it depends on your architecture of script. You can overwrite parametrs with values from config and vice versa.
By the way shflags may be pretty useful in writing such script.

Initiating dynamic variables (variable variables) in bash shell script

I am using PHP CLI through bash shell. Please check Manipulating an array (printed by php-cli) in shell script for details.
In the following shell code I am able to echo the key- value pairs that I get from the PHP script.
IFS=":"
# parse php script output by read command
php $PWD'/test.php' | while read -r key val; do
echo $key":"$val
done
Following is the output for this -
BASE_PATH:/path/to/project/root
db_host:localhost
db_name:database
db_user:root
db_pass:root
Now I just want to initiate dynamic variables inside the while loop so that I can use them like $BASE_PATH having value '/path/to/project/root', $db_host having 'localhost'
I come from a PHP background. I would like something like $$key = $val of PHP
Using eval introduces security risks that must be considered. It's safer to use declare:
# parse php script output by read command
while IFS=: read -r key val; do
echo $key":"$val
declare $key=$val
done < <(php $PWD'/test.php')
If you are using Bash 4, you can use associative arrays:
declare -A some_array
# parse php script output by read command
while IFS=: read -r key val; do
echo $key":"$val
some_array[$key]=$val
done < <(php $PWD'/test.php')
Using process substition <() and redirecting it into the done of the while loop prevents the creation of a subshell. Setting IFS for only the read command eliminates the need to save and restore its value.
You may try using the eval construct in BASH:
key="BASE_PATH"
value="/path/to/project/root"
# Assign $value to variable named "BASE_PATH"
eval ${key}="${value}"
# Now you have the variable named BASE_PATH you want
# This will get you output "/path/to/project/root"
echo $BASE_PATH
Then, just use it in your loop.
EDIT: this read loop creates a sub-shell which will not allow you to use them outside of the loop. You may restructure the read loop so that the sub-shell is not created:
# get the PHP output to a variable
php_output=`php test.php`
# parse the variable in a loop without creating a sub-shell
IFS=":"
while read -r key val; do
eval ${key}="${val}"
done <<< "$php_output"
echo $BASE_PATH

Manipulating an array (printed by php-cli) in shell script

I am a newbie with shell scripts and I learnt a lot today.
This is an extension to this question Assigning values printed by PHP CLI to shell variables
I got the solution to read a variable in my shell script. Now how to manipulate an array? If I prepare an array in my PHP code and print it, and echo in my shell, it displays Array. How to access that array in the shell script? I tried the solution given in how to manipulate array in shell script
With the following code:-
PHP code
$neededConstants = array("BASE_PATH","db_host","db_name","db_user","db_pass");
$associativeArray = array();
foreach($neededConstants as $each)
{
$associativeArray[$each] = constant($each);
}
print $associativeArray;
Shell code
function getConfigVals()
{
php $PWD'/developer.php'
}
cd ..
PROJECT_ROOT=$PWD
cd developer
# func1 parameters: a b
result=$(getConfigVals)
for((cnt=0;cnt<${#result};cnt++))
do
echo ${result[$cnt]}" - "$cnt
done
I get this output:-
Array - 0
- 1
- 2
- 3
- 4
Whereas I want to get this:-
Array
BASE_PATH - /path/to/project
db_host - localhost
db_name - database
db_user - root
db_pass - root
You should debug your PHP script first to produce the valid array content, code
print $associativeArray;
will just get you the following output:
$ php test.php
Array
You can simply print the associative array in a foreach loop:
foreach ( $associativeArray as $key=>$val ){
echo "$key:$val\n";
}
giving a list of variable names + content separated by ':'
$ php test.php
BASE_PATH:1
db_host:2
db_name:3
db_user:4
db_pass:5
As for the shell script, I suggest using simple and understandable shell constructs and then get to the advanced ones (like ${#result}) to use them correctly.
I have tried the following bash script to get the variables from PHP script output to shell script:
# set the field separator for read comand
IFS=":"
# parse php script output by read command
php $PWD'/test.php' | while read -r key val; do
echo "$key = $val"
done
With bash4, you can use mapfile to populate an array and process substitution to feed it:
mapfile -t array < <( your_command )
Then you can go through the array with:
for line in "${array[#]}"
Or use indices:
for i in "${#array[#]}"
do
: use "${array[i]}"
done
You don't say what shell you're using, but assuming it's one that supports arrays:
result=($(getConfigVals)) # you need to create an array before you can ...
for((cnt=0;cnt<${#result};cnt++))
do
echo ${result[$cnt]}" - "$cnt # ... access it using a subscript
done
This is going to be an indexed array, rather than an associative array. While associative arrays are supported in Bash 4, you'll need to use a loop similar to the one in Martin Kosek's answer for assignment if you want to use them.

Accessing variable from ARGV

I'm writing a cPanel postwwwact script, if you're not familiar with the script its run after a new account is created. it relies on the user account variable being passed to the script which i then use for various things (creating databases etc). However, I can't seem to find the right way to access the variable i want. I'm not that good with shell scripts so i'd appreciate some advice. I had read somewhere that the value i wanted would be included in $ARGV{'user'} but this simply gives "root" as opposed to the value i need. I've tried looping through all the arguments (list of arguments here) like this:
#!/bin/sh
for var
do
touch /root/testvars/$var
done
and the value i want is in there, i'm just not sure how to accurately target it. There's info here on doing this with PHP or Perl but i have to do this as a shell script.
EDIT Ideally i would like to be able to call the variable by something other than $1 or $2 etc as this would create issues if an argument is added or removed
..for example in the PHP code here:
function argv2array ($argv) {
$opts = array();
$argv0 = array_shift($argv);
while(count($argv)) {
$key = array_shift($argv);
$value = array_shift($argv);
$opts[$key] = $value;
}
return $opts;
}
// allows you to do the following:
$opts = argv2array($argv);
echo $opts[‘user’];
Any ideas?
The parameters are passed to your script as a hash:
/scripts/$hookname user $user password $password
You can use associative arrays in Bash 4, or in earlier versions of Bash you can use built up variable names.
#!/bin/bash
# Bash >= 4
declare -A argv
for ((i=1;i<=${##};i+=2))
do
argv[${#:i:1}]="${#:$((i+1)):1}"
done
echo ${argv['user']}
Or
#!/bin/bash
# Bash < 4
for ((i=1;i<=${##};i+=2))
do
declare ARGV${#:i:1}="${#:$((i+1)):1}"
done
echo ${!ARGV*} # outputs all variable names that begin with ARGV
echo $ARGVuser
Running either:
$ ./argvtest user dennis password secret
dennis
Note: you can also use shift to step through the arguments, but it's destructive and the methods above leave $# ($1, $2, etc.) in place.
#!/bin/bash
# Bash < 4
# using shift (can use in Bash 4, also)
for ((i=1;i<=${##}+2;i++))
do
declare ARGV$1="$2"
# Bash 4: argv[$1}]="$2"
shift 2
done
echo ${!ARGV*}
echo $ARGVuser
If it's passed as a command-line parameter to the script, it's available as $1 if it's first parameter, $2 for the second, and so on.
Why not start off your script with something like
ARG_USER=$1
ARG_FOO=$2
ARG_BAR=$3
And then later in your script refer to $ARG_USER, $ARG_FOO and $ARG_BAR instead of $1, $2, and $3. That way, if you decide to change the order of arguments, or insert a new argument somewhere other than at the end, there is only one place in your code that you need to update the association between argument order and argument meaning.
You could even do more complex processing of $* to set your $ARG_WHATEVER variables, if it's not always going to be that all of the are specified in the same order every time.
You can do the following:
#!/bin/bash
for var in $argv; do
<do whatver you want with $var>
done
And then, invoke the script as:
$ /path/to/script param1 arg2 item3 item4 etc

Resources