php shell 命令中的 rm -f 安全吗?

Is rm -f in a php shell command safe?

这里没有用户输入,但我还是想检查一下这是否安全:

<?php system('rm /tmp/my-cache/3600/* -f');

是否有任何情况会导致从另一个目录中删除文件?例如,如果该目录由于某种原因不存在会发生什么情况?

我认为它是安全的,但我之前在每分钟运行的 cron 作业中被一段类似(但完全不同)的代码所困扰:

cd /tmp/my-cache/3600
find . -maxdepth 1 -mmin +61 -type f -delete

在某些情况下该文件夹不存在,这意味着 find 而是删除主目录中的所有文件!

(修复方法是将其包装在 if [ -d "/tmp/my-cache/3600" ]; then / fi 块中)

就像我说的,我认为 php system 调用是安全的,我只是想检查是否存在我不知道哪些可能导致问题的情有可原的情况?

rm -f /tmp/my-cache/3600/* 是安全的,如果 /tmp/my-cache/3600/ 为空,则不会删除任何内容。

rm /tmp/my-cache/3600/*(无 -f)的唯一区别是您不会收到此警告:

No such file or directory

...但这并不意味着某些内容已被删除。根据 rm's man page-f 选项会发生这种情况:

If the file does not exist, do not display a diagnostic message or modify the exit status to reflect an error.

...所以 rm 表现得好像它已经删除了一些东西,即使它没有。


find也很安全!

与其检查目录是否存在,然后 cd 进入其中,然后 运行 find,不如使用以下 find 命令:

find /tmp/my-cache/3600 -maxdepth 1 -mmin +61 -type f -delete

...因为它已经为您完成了检查:

find: /tmp/my-cache/3600: No such file or directory