ループで使用したときに間違った場所にzipを出力する

ループで使用したときに間違った場所にzipを出力する

私は多くのディレクトリがあり、それらをすべて圧縮したいと思います。

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

私は使用zipし、期待どおりに動作します。

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

しかし、zshを使用してループで使用すると、zipファイルが別の場所に作成されます。

$ 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/

次のような結果を期待しています。

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

どうなりますか?

ベストアンサー1

出力で確認できます。

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

を実行しているため、for dir in */変数に末尾のスラッシュが含まれます。だからあなたの$dirものはone、それですone/。したがって、を実行すると、zip -r "$dir.zip" "$dir";次のコマンドが実行されます。

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

zip指示に正確に従うことも同様です。私はあなたが望むものは次のように思う。

$ 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

おすすめ記事