循环遍历目录并压缩没有父路径的特定文件夹

时间:2021-04-24 21:10:32

标签: linux bash shell

我正在尝试制作一个 bash 脚本来循环遍历目录中的所有文件夹,并单独压缩我想要的文件夹而不带所有路径,然后选择压缩主题的位置。

from

我可以压缩我想要的文件夹,但输出 zip 文件带有以下内容:

#!/bin/bash

for dir in /MyPersonalFolder/*/*/WhatIWantFolder
do   
   folder_number=$(basename ${dir%/*}) ### basename get the name of this folder [*] 'folder have numbers' /MyPersonalFolder/*/[*]/WhatIWantFolder
   sudo tar -cf "${folder_number}-WhatIWantFolder".tar.gz --absolute-names "$dir"   
   mkdir -p ./backup-theme/ && sudo mv "${folder_number}-theme".tar.gz $_ ### I use this to move zipped folder to specific directory if i can choose where to zip file in the zip command line it's better
done

但我需要的是用这个路径输出文件:

/MyPersonalFolder/0001/0001/WhatIWantFolder

我试图改变这一行中的“$dir”

0001/
  |___WhatIWantFolder/

基名 ${dir%/*}

sudo tar -cf "${folder_number}-WhatIWantFolder".tar.gz --absolute-names "$dir"   

tar 未找到它带有错误的文件夹

sudo tar -cf "${folder_number}-WhatIWantFolder".tar.gz --absolute-names "basename ${dir%/*}"   

1 个答案:

答案 0 :(得分:0)

您可以在运行 tar 时使用 --cd 选项 cd 到另一个目录。

#!/bin/bash

for dir in MyPersonalFolder/*/*/WhatIWantFolder; do
    parent="${dir%/*/*}"
    subdir="${dir#*/*/*}"
    outfile="backup-theme/${subdir/\//-}.tar.gz"

    tar --cd "$parent" -cvzf "$outfile" "$subdir" 
done

tar 文件的目录结构如下所示:

tar -tf backup-theme/0001-WhatIWantFolder.tar.gz
0001/WhatIWantFolder/
0001/WhatIWantFolder/f1