php shell exec的作用与直接运行命令不同 [英] php shell exec acting different to running command directly
问题描述
我有一个php脚本,试图从目录结构中删除所有文件,但将所有内容保留在svn中.我在线上找到了此命令,如果直接将其插入外壳,则可以完美地完成工作
I have a php script that attempts to remove all files from a directory structure, but preserve everything in svn. I found this command online which does the job perfectly if you plug it directly in a shell
find /my/folder/path/ -path \'*/.svn\' -prune -o -type f -exec rm {} +
不幸的是,如果我在php上执行命令shell_exec像这样:
Unfortunately if I perform a shell_exec in php on that command like so:
$cmd = 'find $folderPath -path \'*/.svn\' -prune -o -type f -exec rm {} +';
shell_exec($cmd);
然后,我从中调用php脚本的当前目录中的所有文件也将被删除.
Then all the files in my current directory that I call the php script from are deleted as well.
有人可以解释原因,以及如何解决此问题,以便我可以修复php脚本,使其行为如预期的那样,仅删除指定文件夹中的那些文件
Can someone explain why, and how to fix the issue so that I can fix the php script so it acts like expected, removing only those files in the specified folder
下面是完整的源代码,以防万一我错过了一个愚蠢的错误:
The full source code is below, just in case there is perhaps a silly mistake in there that I have missed:
<?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中解决问题,
Your command looks okay. At least in shell. If you would actually troubleshoot your issue in PHP with a simple
var_dump($cmd);
您会看到错误所在:
$cmd = 'find $folderPath -path \'*/.svn\' -prune -o -type f -exec rm {} +';
仔细观察.提示:一个人不能赚一美元..
这篇关于php shell exec的作用与直接运行命令不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!