Call and run php script from shell script

Solution 1:

The problem in your code is the line:

. "${CONFIG}${i}/test.php"  

Remove the .


Here is another example:

$ ls -l

-rwxrwxr-x 1 bg bg 67 Oct 20 09:42 index.php
-rwxrwxr-x 1 bg bg 68 Oct 20 09:43 test.sh

index.php

<?php
    shell_exec('echo Hello > /tmp/hello.txt');
?>

test.sh

#!/bin/bash
/usr/bin/php index.php

Solution 2:

The problem here is that you are quoting the entiore command you are trying to run as a single variable. As a result, you're not running php with foo.php as an argument but instead are attempting to execute a file called php foo.php. Here's a simpler example to show you what I mean:

$ var1="echo "
$ var2="foo"
$ set -x ## debugging info
$ "$var1$var2"
+ 'echo foo'      ### The shell tries to execute both vars as a single command
bash: echo foo: command not found

$ "$var1" "$var2"
+ 'echo ' foo     ### The shell tries to execute 'echo ' (echo with a space)
bash: echo foo: command not found  

So, the right way is to remove the space and quote each variable separately:

$ var1="echo"
$ var2="foo"
$ "$var1" "$var2"

If you do that though, you'll hit the next error. The . is the source command. That tries to read a shell script and execute it in the current session. You are giving it a php script instead. That won't work, you need to execute it, not source it.

Finally, always avoid using CAPITAL variable names. The shell's reserved variables are capitalized so it's a good idea to always use lower case variable names for your scripts.

Putting all this together (with a few other minor improvements), what you want is something like:

#!/bin/sh

list="/path/to/my/site/dir"
config="/usr/bin/php"

for i in "$list"
do
    "$config" "$i"/test.php
done