Shell
在循環中使用時,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
這是怎麼回事?
您可以在輸出中看到它:
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