用于循环目录的SSH命令除了指定的几个

时间:2010-12-10 18:46:23

标签: bash loops ssh

是否可以通过SSH执行bash命令,该命令循环遍历我指定的多个目录,除了3或4?类似的东西:

删除public_html/outdated/中除/home//home/exception1//home/exception2/

之外的所有目录的/home/exception3/

我在HostGator专用Linux服务器上。

3 个答案:

答案 0 :(得分:3)

这是一行,但为了便于阅读,我将其拆分为

find /home
    \( -wholename '/home/exception1'
    -o -wholename '/home/exception2'
    -o -wholename '/home/exception3' \)
    -prune -o
  -wholename '*/public_html/outdated' -type d
  -exec rm -rvf \{} \;

在运行此操作之前,我强烈建议将-exec rm -rvf \{} \;位替换为-print,以验证它是否仅打印了您要删除的内容。

以下是它的工作原理:find以递归方式查找内容。 \(中的内容... \)' matches directories you want to skip entirely (ie: prune). The standard pattern for using - 修剪is to say what you want to prune out, then - 修剪-o`,然后是您实际想要匹配的内容。

我们希望匹配public_html/outdated目录,这就是-wholename '*/public_html/outdated' -type d的用途。 (-type d表示“是一个目录”)。

最后是我们想要执行的动作。再次使用-print替换此部分,直到您确定它符合您的要求为止。

一个警告:这将吐出一堆形式的警告:

find: `/home/foo/public_html/outdated': No such file or directory

这是因为find正试图进入刚删除的目录。你可以放心地忽略这些 - 尽管有警告,发现仍会继续。

答案 1 :(得分:2)

先测试!

shopt -s extglob
rm -rf /home/!(exception1|exception2|exception3)/public_html/outdated/

答案 2 :(得分:1)

这是一个简单的解决方案 - 可能有更好的方法来实现这一目标。

cd /home
ls */public_html/outdated
你们所有人都应该这样做;你可以使用grep -v从那个

中删除行
ls */public_html/outdated | grep -Ev ^exception1/ | grep -Ev ^exception2/ | grep -Ev ^exception3/

然后使用反引号将这些内容反馈到rm -rf

rm -rf `ls */public_html/outdated | grep -Ev ^exception1/ | grep -Ev ^exception2/ | grep -Ev ^exception3/`

显然你应该在实际删除之前运行中间步骤来验证列表!

请注意,如果您的任何目录中有空格,这可能无效 - 尽管/ home中的用户名不应该。安全的方法是使用find。 (可能有一种方法可以排除查找,但我永远不会记得。)