如何压缩Bash中的所有子文件夹?

时间:2018-09-04 11:14:36

标签: linux bash tar

我是Bash的新手,正在尝试压缩子文件夹,但无法正常工作。

|-- Folder
|   |-- SubFolder1
|   |-- SubFolder2
|   |-- SubFolder3

tar命令之后

|-- Folder
|   |-- SubFolder1
|   |-- SubFolder2
|   |-- SubFolder3
|   |-- SubFolder1.tar.gz
|   |-- SubFolder2.tar.gz
|   |-- SubFolder3.tar.gz

脚本:

#!/bin/bash
DEST=/home/pc/Desktop


for folder in $DEST
do

      tar -czvf "$folder.tar.gz"  $DEST
      #rm -rf "$folder"

done

我该怎么做?

2 个答案:

答案 0 :(得分:0)

需要告知您的for循环要迭代什么。您只是在告诉它顶层目录:

...
DEST=/home/pc/Desktop

for folder in $DEST
...

这需要包含一个通配符,以便Bash知道您想要其下的所有目录:

...
DEST=/home/pc/Desktop

for folder in "$DEST"/*
...

示例

$ mkdir -p Folder/SubFolder{1,2,3}
$ tree Folder/
Folder/
├── SubFolder1
├── SubFolder2
└── SubFolder3

3 directories, 0 files

您的命令:

$ for i in Folder/;do echo "$i";done
Folder/

带有星号(*):

$ for i in Folder/*;do echo "$i";done
Folder/SubFolder1
Folder/SubFolder2
Folder/SubFolder3

使用查找

您可以使用for代替使用tar来生成find的目录,而不是这样:

$ find Folder/ -mindepth 1 -maxdepth 1 -type d | xargs -I {} tar zcvf {}.tar.gz {}
Folder/SubFolder3/
Folder/SubFolder1/
Folder/SubFolder2/

$ ll Folder/
total 24
drwxr-xr-x 2 root root 4096 Sep  4 07:30 SubFolder1
-rw-r--r-- 1 root root  122 Sep  4 08:01 SubFolder1.tar.gz
drwxr-xr-x 2 root root 4096 Sep  4 07:30 SubFolder2
-rw-r--r-- 1 root root  122 Sep  4 08:01 SubFolder2.tar.gz
drwxr-xr-x 2 root root 4096 Sep  4 07:30 SubFolder3
-rw-r--r-- 1 root root  122 Sep  4 08:01 SubFolder3.tar.gz

答案 1 :(得分:0)

请检查代码块中的注释:

#!/bin/bash
DEST=/whatever/whatever/*/  #Note the ending "/" let you get only dirs

for folder in $DEST
do
    #the basename gets the name of current sub-dir
    #instead of fullpath
    tar -czvf "$(basename "$folder").tar.gz"  "$folder"
done

您可能会收到类似“ tar:删除前导” /”或斜杠...之类的错误消息,我记不清确切的措辞了。您可以将-P添加到tar中以忽略它。