我有一个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;
?>
答案 0 :(得分:2)
你的命令看起来没问题。至少在shell中。如果您真的使用简单的
解决PHP中的问题var_dump($cmd);
您会看到错误所在:
$cmd = 'find $folderPath -path \'*/.svn\' -prune -o -type f -exec rm {} +';
答案 1 :(得分:1)
这一切都归结为:
$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 {} +';