Linux Shell Bridge (Passing variables from scripting langauges like PHP to Linux Shell)

Sys Administration

It might sound strange at first but i must say that it's very useful specially if you have shell scripts as part of your application. Usually For making this scripts as automated as possible there should be a way to reuse the application's configurations (ips, passwords , etc) and not having to update a separate configuration file whenever anything changes in the application. It's not limited only to this and can be used to pass any kind of variables.

Although part of the code is written using PHP this technique works for any programming languages (Perl, Java, Python , etc)

The first part of this program is the code which is responsible for generating shell compatible variables (Written in PHP) (Save it as bridge.php) :

#!/usr/bin/php -q

* @desc 
function convertToFlatArray($Array,$Separator='.',$FlattenedKey='') {        
    foreach($Array as $Key => $Value) {
        if(is_Array($Value)) {
        } else {
    return $FlattenedArray;

function __prepareConfigForBash($Array,$Separator='.',$_FlattenedKey='') {        

    foreach ($flatConfig as $optionName=>$optionValue) {
    return $shellConfig;

//Here is our configurations

//And time to convert configurations to bash script format
//Note that cfg is a prefix
echo __prepareConfigForBash($params,'_','cfg');

And the second part is the shell script function that call the above script and import its result in the shell script (Save it as :


# Set the path of the bridge script here

# --(Begin)-- : Import variables from string
cfg_parser () {   
    # convert to line-array
    IFS=$'\n' && ini=( $(php -d allow_call_time_pass_reference=1 -d error_reporting=E_ERROR bridge.php  ) ) 
    ini[0]=''                                # remove first element

    eval "$(echo "${ini[*]}")"               # eval the result
# --(End)-- : Import variables from string

# Lets make sure that it really words
echo "FTP Host is : $cfg_ftp_host"

You can now make the script executable and run it using the following command :

chmod +x

Note : If you don't want to cd into the script's directory you can read my another article for making the shell script paths relative to it location. How to find Linux bash script path (Self Path)

What i like about this solution is even if you want to run the script where you don't have access to the application, you can simply run the following command and copy & paste the result right into your script! :

php bridge.php

Result :


If you ported this script to other programming languages (Python, Perl, etc) let me know as well :)


Your rating: None Average: 4 (2 votes)