【问题标题】:iterate over all files in directory遍历目录中的所有文件
【发布时间】:2021-06-20 18:44:59
【问题描述】:

我正在尝试编写一个 BASH 脚本来遍历目录中的所有文件,如果该文件不是 zip 而不是压缩它

#!/bin/bash

echo "Start"
for f in *
do
        echo "Start loop $f "
        # if .bak backup file exists, read next file
    if [ -${f} = *.zip ]
    then
        echo "Skiping $f file..."
        continue  # read next file and skip the cp command
    fi
        zip $f.zip $f
done
echo "Closing"

我在目录中有以下文件:1, 2, 3.zip, zipper.sh 目录上的脚本输出需要是

1, 1.zip, 2, 2.zip, 3.zip, zipper.sh, zipper.sh.zip

但它也创建了3.zip.zip

【问题讨论】:

  • 我不认为if [ -${f} = *.zip ] 做你认为它做的事情。
  • 看看这个输出:shopt -s extglob; for f in !(*.zip); do echo "$f"; done
  • @Cyrus 我看到了你的命令的输出,但我不明白如何在我的脚本中实现它。
  • @yaodav 阅读 bash 手册并查找有关扩展 glob 或模式的主题。您还必须考虑可能想要或不想覆盖它们的已经存在的 zip 文件。

标签: bash glob


【解决方案1】:

试试下面的代码。

#!/bin/bash

for f in `find . -type f -not -name "*.zip"`;
do
  #echo $f
  zip "$f".zip  $f
done

【讨论】:

  • 文件名中包含空格怎么办?
猜你喜欢
  • 2015-03-05
  • 2018-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-22
  • 2012-06-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多