bash 当“find”返回多个结果时,为什么会触发错误“find:path must precede expression”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27922449/
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 12:10:29  来源:igfitidea点击:

Why does the error "find: paths must precede expression" trigger when multiple results are returned from "find"

linuxbash

提问by Dave

Why does the error find: paths must precede expression: input.txt trigger when multiple results are returned from "find" in subprocess but not when a single result is returned?

当子进程中的“find”返回多个结果而不是返回单个结果时,为什么会出现错误 find:paths must preceto expression: input.txt 触发?

The dir contains three files.

该目录包含三个文件。

ls
input2.txt  input.txt  input.log 

There is only one file matching the find query and the result can be assigned to $foo

只有一个文件匹配查找查询,结果可以分配给 $foo

$ foo=$(find . -name *.log )
echo $foo
./plot.log

When > 1reults are returned find throw's an error.

> 1返回结果时,发现抛出错误。

$ foo=$(find . -name *.txt )
find: paths must precede expression: input.txt

I don't understand why this is happening.

我不明白为什么会这样。

回答by l0b0

You need to quotespecial characters, because globs are expandedbefore running the command:

你需要引用特殊字符,因为在运行命令之前globs 被扩展

find . -name '*.txt'

To see how globbing works, try for example echo *.txt- it will onlyactually print *.txtif there are no files in the current directory ending with .txt.

要了解通配符的作品,尝试例如echo *.txt-这将实际打印*.txt,如果有在当前目录中没有文件结尾.txt