2012-12-24 86 views
2

我有一個php腳本,它嘗試從目錄結構中刪除所有文件,但是保留svn中的所有文件。我發現這個命令在網上,如果你直接在外殼php shell exec的作用與直接運行命令不同

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

像往常一樣,多餘的短語和問候是:多餘的。如果你不是在尋求幫助,我們不希望你在這裏發帖。 – hakre

+0

道歉,我在尋求幫助。有人可以解釋爲什麼,以及如何解決這個問題,以便我可以修復php腳本,使其行爲像預期的那樣,只刪除指定文件夾中的文件。 – Programster

+0

一切都好,這隻需要基本的故障排除,因爲你需要看看你的代碼是否符合你的期望。你可以通過在它們之間加入變量來檢查它們是否包含你認爲應該存在的內容。 – hakre

回答

2

你的命令看起來沒問題。至少在殼牌。如果你實際上有一個簡單的

var_dump($cmd); 

排查PHP您的問題,您會看到您的錯誤在於:

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

仔細查看。提示:A single can't make a double for a dollar

+0

對不起,給你的提示awnser :) –

+0

你寵壞了它:) – hakre

+0

謝謝,完全忘了那個歡呼聲 – Programster

1

這一切都歸結爲:由於您使用單引號的變量$folderPath不改變

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

。所以,你正在執行

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 {} +';

相關問題