Shell脚本在创建zip文件时消除完整路径。

huangapple go评论46阅读模式
英文:

Shell Script Eliminate full path while creating zip

问题

我有一个目录路径 /root/Archive/EKS/data - 在这个 data 文件夹下有一些文本文件,我的目标是需要将整个 data 目录压缩,并将压缩文件保留在相同的位置 (/root/Archive/EKS/data)。

但是下面的脚本在我们预期的情况下工作,但是当我解压缩文件夹时,文件夹路径从 /root/Archive/EKS/data 开始重复,但我不想根据完整路径创建压缩文件,而是希望基于 data 目录创建压缩文件。

└─# tree root/
root/
└── Archive
    └── EKS
        └── validate-file
3 directories, 0 files
startdir=(
"/root/Archive/EKS/data"
)

for dir in "${startdir[@]}" ; do
    for sub_dir in "$dir"/*/ ; do
        zip "${sub_dir%/}.zip" "$sub_dir"
    done
done

你能指导我在哪里出错吗?

英文:

I have directory path /root/Archive/EKS/data - Under this data folder I have some text file, my goal is need take entire data directory and keep the zipped file into same place (/root/Archive/EKS/data.

But the below is script is working as we expected but when I'm doing unzipping the folder path start from /root/Archive/EKS/data, its repeating but I don't want to make zip based on full path instead it needs to create zip file based on data directory only.

└─# tree root/
root/
└── Archive
    └── EKS
        └── validate-file
3 directories, 0 files
startdir=(
"/root/Archive/EKS/data"
)

for dir in "${startdir[@]}" ; do
    for sub_dir in "$dir"/*/ ; do
        zip "${sub_dir%/}".zip "$sub_dir"
    done
done

can you please guide me where I'm missing it.

答案1

得分: 2

你可以这样做:

#!/bin/bash

startdir="/root/Archive/EKS/data"

cd "$startdir" || exit

for sub_dir in */ ; do
    zip -r "${sub_dir%/}.zip" "$sub_dir"
done

cd $startdir 命令将工作目录更改为/root/Archive/EKS/data。

然后,我们遍历data目录中的每个子目录(*/),并创建zip文件。

希望有所帮助。

英文:

You can do something like this

    #!/bin/bash
    
    startdir="/root/Archive/EKS/data"
    
    cd "$startdir" || exit
    
    for sub_dir in */ ; do
        zip -r "${sub_dir%/}.zip" "$sub_dir"
    done

cd $startdir command changes the working directory to /root/Archive/EKS/data.

Then we iterate through each subdirectory (*/) within the data directory and create the zip file.

hope it helps.

huangapple
  • 本文由 发表于 2023年5月24日 22:51:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76324816.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定