避免匹配.和 .. 在 POSIX shell 中循环文件时 [英] Avoid matching . and .. when looping through files in POSIX shell

查看:44
本文介绍了避免匹配.和 .. 在 POSIX shell 中循环文件时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对目录中的每个文件做一些事情,所以我有

I want to do something to every file in a directory, so I have

for f in /path/* /path/.*; do
  [ -e "$f" ] || continue
  do_thing "$f"
done

不幸的是,这也匹配了 ...,这在本例中是不可取的.如何避免匹配 ...?

Unfortunately, this also matches . and .., which is undesirable in this case. How can I avoid matching . and ..?

推荐答案

要对当前目录中的每个文件运行 do_thing,请尝试:

To run do_thing on every file in the current directory, try:

find /path -maxdepth 1 -type f -exec do_thing {} \;

这个方法避免了循环,避免解析ls.

This method avoids looping and avoids parsing ls.

  • 找到/path

这会启动一个 find 命令并告诉 find 在目录 /path 中查找.

This starts a find command and tells find to look in directory /path.

-maxdepth 1

这告诉 find 只在当前目录中查找,而不是进入子目录.

This tells find to look only in the current directory and not to descend into subdirectories.

-type f

这告诉 find 我们只查找常规文件(而不是目录).

This tells find that we are only looking for regular files (not directories).

-exec do_thing {} \;

这会在找到的每个文件上运行命令 do_thing.

This runs command do_thing on every file found.

这篇关于避免匹配.和 .. 在 POSIX shell 中循环文件时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆