为什么我会收到二进制操作员的预期错误

发布于 2025-01-23 20:27:06 字数 47 浏览 2 评论 0原文

我正在尝试编写一个shell脚本以检查是否存在使用if语句以.txt结尾的文件。

I'm trying to write a shell script to check if there's a file existing that ends with .txt using an if statement.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浮世清欢 2025-01-30 20:27:06

在单个支架条件中,所有

审核构建体对所给出的参数的 number 进行:-f期望完全遵循一个参数,一个文件名。显然,您的*。TXT模式匹配多个文件。

如果您的外壳是bash,您可以做到

files=(*.txt)
if (( ${#files[@]} > 0 )); then ...

或更便宜:

count=0
for file in *.txt; do 
  count=1
  break
done
if [ "$count" -eq 0 ]; then
  echo "no *.txt files"
else
  echo "at least one *.txt file"
fi

我终于得到了您的观点。我一直给您一些不完整的建议。这就是您需要的:

for f in *.txt; do
  if [ -f "$f" ]; then
    do_something_with "$f"
  fi
done

原因:如果有没有匹配模式的文件,则Shell 将Patten作为平单字符串。在循环的第一次迭代中,我们具有f =“*。txt”mv以“未找到文件”响应。

我习惯于使用处理此边缘情况的nullglob选项。

Within single bracket conditionals, all of the Shell Expansions will occur, particularly in this case Filename expansion.

The condional construct acts upon the number of arguments it's given: -f expects exactly one argument to follow it, a filename. Apparently your *.txt pattern matches more than one file.

If your shell is bash, you can do

files=(*.txt)
if (( ${#files[@]} > 0 )); then ...

or, more portably:

count=0
for file in *.txt; do 
  count=1
  break
done
if [ "$count" -eq 0 ]; then
  echo "no *.txt files"
else
  echo "at least one *.txt file"
fi

I finally get your perspective now. I've been giving you some incomplete advice. This is what you need:

for f in *.txt; do
  if [ -f "$f" ]; then
    do_something_with "$f"
  fi
done

The reason: if there are no files matching the pattern then the shell leaves the patten as a plain string. On the first iteration of the loop, we have f="*.txt" and mv responds with "file not found".

I'm used to working in bash with the nullglob option that handles this edge case.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文