bash:find命令中的复杂测试

Ste*_*ski 1 linux bash find

我想做的事情如下:

find . -type f -exec test $(file --brief --mime-type '{}' ) == 'text/html' \; -print 
Run Code Online (Sandbox Code Playgroud)

但我无法弄清楚引用或逃避测试的args的正确方法,尤其是'$('...')'.

Bri*_*ell 9

你不能简单地转义传递它们的参数find.

任何shell扩展都将 find运行之前发生.find不会通过shell传递它的参数,所以即使你逃避shell扩展,一切都只会被视为test命令的文字参数,而不是像你期望的那样由shell扩展.

实现你想要的最好的方法是编写一个简短的shell脚本,它将文件名作为参数,然后使用-exec:

find . -type f -exec is_html.sh {} \; -print
Run Code Online (Sandbox Code Playgroud)

is_html.sh:

#!/bin/sh

test $(file --brief --mime-type "$1") == 'text/html'
Run Code Online (Sandbox Code Playgroud)

如果您真的希望在一行中使用它,而不使用单独的脚本,则可以sh直接从find以下位置调用:

find . -type f -exec sh -c 'test $(file --brief --mime-type "$0") == "text/html"' {} \; -print
Run Code Online (Sandbox Code Playgroud)