linux - Linux 中的 for 循环在不存在文件时将模式视为文件名

标签 linux bash for-loop

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

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

它返回的是这样的:

*.20191017.*

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

有人可以帮忙吗?

最佳答案

找到这个异常的原因(来源: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

关于linux - Linux 中的 for 循环在不存在文件时将模式视为文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58637568/

相关文章:

bash - bash 中带有变量、大括号和散列字符的 ${0##...} 语法是什么意思?

bash - 如何在 find 和 bash -c 中传递变量?

java - 对于循环崩溃我的 android 应用程序

c - 我如何与 Cygwin 相处融洽?

python - Python 中的嵌套循环

c++ - 我应该通过迭代器还是通过访问运算符来迭代 vector ?

c++ - OpenGL 三角形未渲染

linux - 在 Linux 中一个接一个地调度作业

linux - 捕获SSH客户端中的执行日志?

linux - 如何在 Linux 中通过 netstat -i 获取队列字段?