PHP shell执行的行为不同于直接运行命令


php shell exec acting different to running command directly

我有一个php脚本,它试图从目录结构中删除所有文件,但保留svn中的所有文件。我在网上找到了这个命令,如果你直接把它插入到shell

中,它可以完美地完成这项工作。
find /my/folder/path/ -path ''*/.svn'' -prune -o -type f -exec rm {} +

不幸的是,如果我在php中对该命令执行shell_exec,像这样:

$cmd = 'find $folderPath -path ''*/.svn'' -prune -o -type f -exec rm {} +';
shell_exec($cmd);

然后我当前目录中所有调用php脚本的文件也会被删除。

有人能解释为什么,以及如何解决这个问题,以便我可以修复php脚本,使其像预期的那样,只删除指定文件夹

中的那些文件

完整的源代码如下,只是以防万一有一个愚蠢的错误在那里,我错过了:

<?php
# This script simply removes all files from a specified folder, that aren't directories or .svn 
# files. It will see if a folder path was given as a cli parameter, and if not, ask the user if they 
# want to remove the files in their current directory.
$execute = false;
if (isset($argv[1]))
{
    $folderPath = $argv[1];
    $execute = true;
}
else
{
    $folderPath = getcwd();
    $answer = readline("Remove all files but not folders or svn files in $folderPath (y/n)?" . PHP_EOL);
    if ($answer == 'Y' || $answer == 'y')
    {
        $execute = true;
    }
}
if ($execute)
{
    # Strip out the last / if it was given by accident as this can cause deletion of wrong files
    if (substr($folderPath, -1) != '/')
    {
        $folderPath .= "/";
    }
    print "Removing files from $folderPath" . PHP_EOL;
    $cmd = 'find $folderPath -path ''*/.svn'' -prune -o -type f -exec rm {} +';
    shell_exec($cmd);
}
else
{
    print "Ok not bothering." . PHP_EOL;
}
print "Done" . PHP_EOL;
?>

您的命令看起来不错。至少在外壳上是这样。如果你想用一个简单的

来解决PHP中的问题
var_dump($cmd);

你会看到你的错误所在:

$cmd = 'find $folderPath -path ''*/.svn'' -prune -o -type f -exec rm {} +';

仔细看。提示:单人间不能换一美元的双人间。

这一切都归结为:

$cmd = 'find $folderPath -path ''*/.svn'' -prune -o -type f -exec rm {} +';
shell_exec($cmd);

由于您使用单引号,因此变量$folderPath不会更改。所以你在执行

find $folderPath -path '*/.svn' -prune -o -type f -exec rm {} +
不是

find /my/folder/path/ -path ''*/.svn'' -prune -o -type f -exec rm {} +

使用双引号或$cmd = 'find '.$folderPath.' -path ''*/.svn'' -prune -o -type f -exec rm {} +';