在 linux 中,如何将特定的子目录压缩到它们自己的名为父目录名称的 zip 文件中,并将它们全部输出到一个目录中?

In linux, how can I zip specific sub directories into their own zip files named parent directory name and output them all into a single directory?

所以我看到类似的问题回答了我的部分问题,但没有达到我需要的特定水平。这是我正在尝试做的事情的总体要点。

我正在将一堆网站迁移到新服务器。目前,它们都位于 /srv/www/

每个站点在该目录名称后都有自己的文件夹,例如 /srv/www/domain1.com/srv/www/domain2.com.

并且在每个 domain.com 目录中都有名为 html.

的 public 网络目录

我想做的是 cd 进入 /srv/www 然后 运行 一个命令或 bash 脚本将循环进入每个 domain.com/html 目录并压缩目录的内容该目录,然后将其输出为 /srv/web_backup/domain.com.zip 中的 zip 名称 domain.com.zip。同样,我只想要内容。当我解压缩文件时,我不希望它输出到 html/{contents}.

在这种情况下,domain.com 是一个示例,但每个文件夹都有自己的名称。

如果我手动执行此操作,一旦我进入 /srv/www/domain.com/html 我将 运行 命令 zip -r /srv/web_backup/domain.com.zip . .htaccess 这就是我想要的 运行 获取所有文件、目录和 .htaccess 文件。

总而言之,我想单独压缩每个 /srv/www/{domain.com}/html 的内容,而不是目录,并将它们命名为 {domain.com}.ziphtml 文件夹的父目录)然后将这些 zip 文件保存到 /srv/web_backup/domain.com.zip

感谢任何帮助,因为我并不谦虚地承认这超出了我的 Linux 知识或能力。

我认为您已经大致描述了这些步骤。您只需要将它们放入脚本中即可。类似于:

#!/bin/bash

cd /srv/www
for domain in *; do
(
cd $domain/html &&
zip -r /srv/web_backup/$domain.zip . .htaccess
)
done

稍微分解一下:

# change into the /srv/www directory
cd /srv/www

# for each domain in this directory (we're largely assuming here that
# this directory contains only directories representing domains you
# want to backup).
for domain in *; do

# a (...) expression runs the included commands in a subshell, so
# that when we exit we're back in /srv/www.
(
# change into the html directory and, if that was successful, update
# your zip file.
cd $domain/html &&
zip -r /srv/web_backup/$domain.zip .
)

done

这只是解决此特定问题的一种方法。你也可以这样写:

#!/bin/sh

find /srv/www/* -maxdepth 0 -type d -print0 |
xargs -0 -iDOMAIN sh -c 'cd "DOMAIN/html" && zip -r "/srv/www/DOMAIN.zip" .

它做的事情大致相同,但巧妙地利用了 findxargs