Search code examples
phpbashshellexec

How to pass a varible through a php file to bash script


I need to run a bash script from php file. Here is my try...

$old_path = getcwd();
chdir('/home/svradmin/scripts');
$output = shell_exec('./testbash.sh');
chdir($old_path);

My testbash.sh as follows..

#!/bin/bash
echo "Hello World"

This works fine... Now I need to pass an variable from my php function and according to that the bash script should run.. lets say as an example..

   function fcn1() {
    $old_path = getcwd();
    chdir('/home/svradmin/scripts');
    $output = shell_exec('./testbash.sh');//need to pass variable 'fcn1'
    chdir($old_path);
    }



   function fcn2() {
    $old_path = getcwd();
    chdir('/home/svradmin/scripts');
    $output = shell_exec('./testbash.sh');//need to pass variable 'fcn2'
    chdir($old_path);
    }

So the bash script need to change as below,

     #!/bin/bash
//If variable fcn1 received
    echo "Hello World!! fcn1 has executed.."

//If variable fcn2 received
    echo "Hello World!! fcn2 has executed.."

Solution

  • EXAMPLE

    Just put your variable(s) after the call --

    $output = shell_exec('./testbash.sh your_var_1 your_var_2');
    

    Then in your bash script:

    #!/bin/bash
    
    var1=$1
    var2=$2
    
    echo "Hello World, var 1 is $var1 and var 2 is $var2"
    

    UPDATE

    So your function would look like:

    function fcn2() {
        $old_path = getcwd();
        chdir('/home/svradmin/scripts');
        $var = "Hello Hello";
        // Or as Fravadona suggested:
        $var = escapeshellarg("Hello Hello");
        $output = shell_exec("./testbash.sh $var");
        chdir($old_path);
        return $output;
    }
    
    function fcn1() {
        $old_path = getcwd();
        chdir('/home/svradmin/scripts');
        $var = "Hello";
        // Or as Fravadona suggested:
        $var = escapeshellarg("Hello");
        $output = shell_exec("./testbash.sh $var");
        chdir($old_path);
        return $output;
    }
    
    echo fcn1();
    echo fcn2();
    

    And your bash ..

    #!/bin/bash
    
    var=$1
    
    echo "Hello World!! $var has executed.."