Print array value in bash by PHP shell_exec

Asked

Viewed 208 times

2

I have another script, but I simplified it for this to simulate the problem that persists.

test sh.

#!/bin/bash
ARRAY=('like' 'a' 'stone')
echo ${ARRAY[0]}

In the file below, in another moment I already made sure that the shell_exec is actually running the above command.

index php.

<?php
$comando = file_get_contents("teste.sh");
echo "<pre>";
var_dump(shell_exec($comando));
echo "</pre>";

Here I’m waiting for you to print like, but the result always comes null as below.

Exit

NULL

But if I change mine teste.sh to just php -v, it prints the version of my PHP. What is not what I want, but serves as strip web.

Exit

string(235) "PHP 5.5.9-1ubuntu4.17 (cli) (built: May 19 2016 19:05:57) 
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies
    with Zend OPcache v7.0.3, Copyright (c) 1999-2014, by Zend Technologies
"

Then I get cranky, like he’s not able to print what I’m waiting for ? What am I doing wrong ?

1 answer

3


You’ve done nothing wrong.

This problem happens due to script be interpreted differently in two different environments.

When executing ./teste1.sh the system will look at the shebang, which in this case is #!/bin/bash and will execute the script using /bin/bash. If you run it by typing: sh script1.sh it will run using the /bin/sh.

No Ubuntu, /bin/sh is typically a shortcut to /bin/dash (see: ls -l /bin/sh) one Bourne shell that can’t stand it arrays, and that is the origin of the problem.

Opening a new terminal window CTRLAltT the environment will probably be /bin/bash, in PHP when running function shell_exec the script will probably run using /bin/sh. Test the code:

<?php

echo shell_exec("echo $0"); // sh?

To solve this, you must execute the script using the /bin/bash, see below two forms:

  1. Execute the script using the bash:

    <?php
    
    $conteudo = file_get_contents("script1.sh");
    echo shell_exec("bash -c '$conteudo'");
    

    To option -c indicates to the bash to read variable commands $conteudo.

  2. Indicate the bash and the file directly on function shell_exec():

    <?php
    
    echo shell_exec("bash script1.sh");
    
  • 1

    Opá, Deu certinho. You saved my life. Thank you @zekk. I chose to use more the first way.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.