为什么 `rm -f !(/var/www/wp)` 将文件留在 /var/www 中?

sho*_*key 5 shell bash rm

为什么rm -f !(/var/www/wp)命令没有效果?我想删除 中的所有文件/var/www,除了/var/www/wp应该保留的目录。

root@born:~# ls  /var/www
authorize.php  index.html          INSTALL.txt      README.txt  UPGRADE.txt
CHANGELOG.txt  index.php           LICENSE.txt      robots.txt  web.config
COPYRIGHT.txt  INSTALL.mysql.txt   MAINTAINERS.txt  scripts wp
cron.php       INSTALL.pgsql.txt   misc             sites       xmlrpc.php
drupal         install.php         modules          themes
includes       INSTALL.sqlite.txt  profiles         update.php
root@born:~# rm  -f  !(/var/www/wp)
root@born:~# ls  /var/www
authorize.php  index.html          INSTALL.txt      README.txt  UPGRADE.txt
CHANGELOG.txt  index.php           LICENSE.txt      robots.txt  web.config
COPYRIGHT.txt  INSTALL.mysql.txt   MAINTAINERS.txt  scripts wp
cron.php       INSTALL.pgsql.txt   misc             sites       xmlrpc.php
drupal         install.php         modules          themes
includes       INSTALL.sqlite.txt  profiles         update.php
Run Code Online (Sandbox Code Playgroud)

Mic*_*mer 37

如果您正在运行 bash ?4.3,那么如果您有备份,现在是寻找它们的好时机

我假设您正在使用 Bash。该!(...)文件名扩展模式扩展到不模式匹配每一个现有路径在它的使用点。那是:

echo rm  -f  !(/var/www/wp)
Run Code Online (Sandbox Code Playgroud)

扩展到当前目录中不是“/var/www/wp”的每个文件名。即当前目录中的每个文件。本质上,你跑rm -f *进去了~不要运行rm上面的命令

为了得到你想要的效果,使用该模式只为你想它(不)来匹配路径的一部分,就像你的*{a,b,c}或任何其他模式。命令:

echo rm -f /var/www/!(wp)
Run Code Online (Sandbox Code Playgroud)

将打印出您要运行的命令。

老实说,我不建议以这种方式做事 - 它很容易出现您在这里和其他人遇到的那种问题。有的东西find更容易遵循。至少,echo运行之前的命令,你会看到发生了什么。

  • 好答案。我还要添加:在删除任何内容之前,至少将 `cd` 添加到目录中。从远处移除东西总是很危险的(特别是如果涉及到相对路径或球体)。 (2认同)

cuo*_*glm 9

您可以阅读Michael Homer 的回答以了解原因。

要删除/var/wwwexclude中的所有内容wp,POSIXly:

find /var/www -path /var/www/wp -prune -o ! -path /var/www -exec rm -rf {} +
Run Code Online (Sandbox Code Playgroud)