使用 ls 和 find 在 bash 脚本中循环文件的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13830036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:00:35  来源:igfitidea点击:

Difference between using ls and find to loop over files in a bash script

bashunixfindls

提问by FrenchKheldar

I'm not sure I understand exactly why:

我不确定我完全理解为什么:

for f in `find . -name "strain_flame_00*.dat"`; do
   echo $f
   mybase=`basename $f .dat`
   echo $mybase
done

works and:

作品和:

for f in `ls strain_flame_00*.dat`; do
   echo $f
   mybase=`basename $f .dat`
   echo $mybase
done

does not, i.e. the filename does not get stripped of the suffix. I think it's because what comes out of lsis formatted differently but I'm not sure. I even tried to put evalin front of ls...

不会,即文件名不会被去除后缀。我认为这是因为输出的ls格式不同,但我不确定。我什至试图把evalls放在前面...

回答by glenn Hymanman

The correct way to iterate over filenames here would be

在这里迭代文件名的正确方法是

for f in strain_flame_00*.dat; do
   echo "$f"
   mybase=$(basename "$f" .dat)
   echo "$mybase"
done

Using forwith a glob pattern, and then quoting all references to the filename is the safest way to use filenames that may have whitespace.

使用forglob 模式,然后引用对文件名的所有引用是使用可能有空格的文件名的最安全方法。

回答by John Greene

First of all, never parse the output of the lscommand.

首先,永远不要解析ls命令的输出。

If you MUST use lsand you DON'T know what lsalias is out there, then do this:

如果您必须使用ls并且您不知道ls那里有什么别名,请执行以下操作:

(
COLUMNS=
LANG=
NLSPATH=
GLOBIGNORE=
LS_COLORS=
TZ=
unset ls
for f in `ls -1 strain_flame_00*.dat`; do
  echo $f
  mybase=`basename $f .dat`
  echo $mybase
done
)

It is surrounded by parenthesis to protect existing environment, aliases and shell variables.

它用括号括起来以保护现有环境、别名和 shell 变量。

Various environment names were NUKED (as lsdoes look those up).

各种环境名称都是 NUKED(就像ls查找那些名称一样)。

One unalias command (self-explanatory).

一个 unalias 命令(不言自明)。

One unset command (again, protection against scrupulous over-lording 'ls' function).

一个未设置的命令(再次,防止严格的霸道'ls' 功能)。

Now, you can see why NOT to use the 'ls'.

现在,您可以明白为什么不使用“ls”了。

回答by sampson-chen

Another difference that hasn't been mentioned yet is that findis recursive search by default, whereas lsis not. (even though both can be told to do recursive / non-recursive through options; and findcan be told to recurse up to a specified depth)

另一个尚未提及的区别find是默认情况下是递归搜索,而ls不是。(即使两者都可以通过选项被告知进行递归/非递归;并且find可以被告知递归到指定的深度)

And, as others have mentioned, if it can be achieved by globbing, you should avoid using either.

而且,正如其他人所提到的,如果可以通过globbing实现,则应避免使用任何一个。