Search code examples
phplinuxbashunixxampp

Syntax error near unexpected token `(' when running shell script from XAMPP


I'm trying to send a shell command directly from an index.php using the exec function as follows:

exec('shopt -s extglob && cd /opt/lampp/htdocs/testes/xml/ && rm !(*.xml)');

However xampp returns an error in the log:

sh: -c: line 1: syntax error near unexpected token `('
sh: -c: line 1: `rm !(*.xml)'

I already gave permission for xampp to send commands via exec to the machine. Other commands like just removing files without the !() criteria works fine.

When I write rm !(*.xml) directly through the linux terminal works normally.


Solution

  • The error message is sh:...

    shopt -s extglob and extended globbing are bash extensions.

    The exec function seems to use a POSIX shell, not bash, so you cannot directly use bash specific code.

    Try something like

    exec('bash -c "shopt -s extglob && cd /opt/lampp/htdocs/testes/xml/ && rm !(*.xml)"');
    

    or maybe even better put your code into a bash script file with interpreter specification

    #!/bin/bash
    

    and use

    exec('/path/to/your_script');