2

I have many directories and I want to zip them all.

$ mkdir -p one two three
$ touch one/one.txt two/two.txt three/three.txt
$ ls -F
one/  three/  two/

I use zip and it works as intended:

$ zip -r one.zip one
  adding: one/ (stored 0%)
  adding: one/one.txt (stored 0%)
$ ls -F
one/  one.zip  three/  two/

But when I used this in a loop using zsh, zip files are created elsewhere.

$ for dir in */; do
for> echo "$dir";   
for> zip -r "$dir.zip" "$dir";
for> done   
one/
  adding: one/ (stored 0%)
  adding: one/one.txt (stored 0%)
three/
  adding: three/ (stored 0%)
  adding: three/three.txt (stored 0%)
two/
  adding: two/ (stored 0%)
  adding: two/two.txt (stored 0%)
$ find . -name "*.zip"
./three/.zip
./two/.zip
./one/.zip
$ ls -F
one/  three/  two/

I expected an output like this:

$ ls -F
one/  one.zip  three/  three.zip  two/  two.zip

What's going on?

1 Answer 1

3

You can see it in your output:

for dir in */; do
for> echo "$dir";   
for> zip -r "$dir.zip" "$dir";
for> done   
one/
[ . . . ]

Since you are doing for dir in */, the variable includes the trailing slash. So your $dir isn't one, it is one/. Therefore, when you run zip -r "$dir.zip" "$dir";, you are running this:

zip -r "one/.zip" "one";

So zip is doing exactly what you tell it to do. What I think you want is something like this instead:

$ for dir in */; do dir=${dir%/}; echo zip -r "$dir.zip" "$dir"; done
zip -r one.zip one
zip -r three.zip three
zip -r two.zip two
6
  • It's still the same. Apr 16, 2021 at 15:47
  • @AmirA.Shabani did you run it with the echo or did you remove the echo?
    – terdon
    Apr 16, 2021 at 15:55
  • I did both. With echo it produces an output like this: zip -r one/.zip one/. Apr 16, 2021 at 15:56
  • 2
    @AmirA.Shabani for zsh (and yes, please remember to mention things like that, they change everything and you had explicitly tagged the question with bash!) change the dir=${dir///} to dir=${dir//\/} and it should work.
    – terdon
    Apr 16, 2021 at 16:01
  • 2
    Or, even better, what @rowboat suggested (thanks!) and which I have now added to my answer since that will work on both bash and zsh (and pretty much everything else).
    – terdon
    Apr 16, 2021 at 16:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.