【问题标题】:for loop in Linux treats pattern as filename when no files exist当不存在文件时,Linux 中的 for 循环将模式视为文件名
【发布时间】:2020-02-26 11:20:05
【问题描述】:

我在没有文件的目录中运行了以下内容:

for file in *.20191017.*;do echo ${file}; done

它返回的是这样的:

*.20191017.*

这有点尴尬,因为这只是一个模式,而不是文件名本身。

有人可以帮忙吗?

【问题讨论】:

  • 你打算做什么?这段代码的目的对我来说有点不清楚。
  • @user2442590 :这并不尴尬,但记录了行为。您必须启用 nullglob,如 bash 手册页中所述。

标签: linux bash for-loop


【解决方案1】:

for 循环只是遍历in; 之间的单词(可能被bash 扩展)。这里,file 只是变量名。如果您想在所有实际存在的文件之间进行迭代,例如,您可以添加一个if 来检查${file} 是否真的存在:

for file in *.20191017.*
do
   if [ -e "${file}" ]
   then
      echo ${file}
   fi
done

或者您可以使用,例如,find

find . -name '*.20191017.*' -maxdepth 1

-maxdepth 1avoid recursion

【讨论】:

【解决方案2】:

找到这个异常的原因(来源:https://www.cyberciti.biz/faq/bash-loop-over-file/

您可以在循环中进行文件名扩展,例如处理当前目录中的所有pdf文件:

for f in *.pdf; do
    echo "Removing password for pdf file - $f"
done

但是,上述语法存在一个问题。如果当前目录中没有 pdf 文件,它将扩展为 *.pdf(即 f 将设置为 *.pdf”)。为了避免这个问题,在 for 循环之前添加以下语句:

#!/bin/bash
# Usage: remove all utility bills pdf file password 
shopt -s nullglob # expands the glob to empty string when there are no matching files in the directory.
for f in *.pdf; do
    echo "Removing password for pdf file - $f"
    pdftk "$f" output "output.$f" user_pw "YOURPASSWORD-HERE"
done

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-27
    • 2013-12-31
    • 2017-07-11
    • 2013-01-08
    • 1970-01-01
    • 2017-12-04
    • 2020-07-19
    • 1970-01-01
    相关资源
    最近更新 更多