How to compress all subfolder in Bash?
我刚接触bash,正在尝试压缩子文件夹,但它不起作用。
1 2 3 4 | |-- Folder | |-- SubFolder1 | |-- SubFolder2 | |-- SubFolder3 |
在
1 2 3 4 5 6 7 | |-- Folder | |-- SubFolder1 | |-- SubFolder2 | |-- SubFolder3 | |-- SubFolder1.tar.gz | |-- SubFolder2.tar.gz | |-- SubFolder3.tar.gz |
脚本:
1 2 3 4 5 6 7 8 9 10 11 | #!/bin/bash DEST=/home/pc/Desktop for folder in $DEST do tar -czvf"$folder.tar.gz" $DEST #rm -rf"$folder" done |
我该怎么做?
请检查代码块中的注释:
1 2 3 4 5 6 7 8 9 | #!/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:删除前导"/"或斜线…"的信息,我记不清确切的措辞。你可以在你的tar中添加
你的
1 2 3 4 5 | ... DEST=/home/pc/Desktop for folder in $DEST ... |
这需要包含一个通配符,以便bash知道您想要它下面的所有目录:
1 2 3 4 5 | ... DEST=/home/pc/Desktop for folder in"$DEST"/* ... |
例子
1 2 3 4 5 6 7 8 | $ mkdir -p Folder/SubFolder{1,2,3} $ tree Folder/ Folder/ ├── SubFolder1 ├── SubFolder2 └── SubFolder3 3 directories, 0 files |
你的命令:
1 2 | $ for i in Folder/;do echo"$i";done Folder/ |
有了星星(
1 2 3 4 | $ for i in Folder/*;do echo"$i";done Folder/SubFolder1 Folder/SubFolder2 Folder/SubFolder3 |
使用查找
不使用
1 2 3 4 5 6 7 8 9 10 11 12 13 | $ 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 |