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

Blog
Linux
PHP
Programming
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) :

<?php
#!/usr/bin/php -q

/**
* @desc 
*/
function convertToFlatArray($Array,$Separator='.',$FlattenedKey='') {        
    $FlattenedArray=Array();
    foreach($Array as $Key => $Value) {
        if(is_Array($Value)) {
            $_FlattenedKey=(strlen($FlattenedKey)>0?$FlattenedKey.$Separator:"").$Key;
            $FlattenedArray=array_merge(
                $FlattenedArray,
                convertToFlatArray($Value,$Separator,$_FlattenedKey)
            );                
        } else {
            $_FlattenedKey=(strlen($FlattenedKey)>0?$FlattenedKey.$Separator:"").$Key;
            $FlattenedArray[$_FlattenedKey]=$Value;
        }
    }
    return $FlattenedArray;
}

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

    //$flatConfig=cmfcArray::convertToFlatArray($Array,$Separator,$_FlattenedKey);
    $flatConfig=convertToFlatArray($Array,$Separator,$_FlattenedKey);
    
    $shellConfig='';
    foreach ($flatConfig as $optionName=>$optionValue) {
        $shellConfig.="$optionName=\"".addslashes($optionValue)."\"\n";
    }
    
    return $shellConfig;
}


//Here is our configurations
$params['serverIp']='23.2.3.23';
$params['ftp']=array(
    'host'=>'myhost.com',
    'username'=>'ftpusername',
    'password'=>'ftppassword',
    'locations'=>array(
        'files'=>'/files',
        'cache'=>'/cache',
    )
);

//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 script.sh) :

#!/bin/bash

# Set the path of the bridge script here
scriptPath="bridge.php";

# --(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
}
cfg_parser
# --(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 hello.sh
./script.sh

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 :

cfg_serverIp="23.2.3.23"
cfg_ftp_host="myhost.com"
cfg_ftp_username="ftpusername"
cfg_ftp_password="ftppassword"
cfg_ftp_locations_files="/files"
cfg_ftp_locations_cache="/cache

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

Resources

Your rating: None Average: 2.1 (17 votes)