如何在最小的 shell 中递归搜索目录(没有 grep、find 等)?
我正在使用运行 QNX 的嵌入式系统,该系统具有精简的 shell (KSH)。
我想找到文件系统上与以下内容匹配的所有运行所有可执行文件:
*/shle/*-*_test
“shle”目录可能会出现在根目录下最多 4 层。我当前的方法是运行以下命令:
for shle in ./shle ./*/shle ./*/*/shle ./*/*/*/shle
do
for exe in $shle/*-*_test
do
echo running: $exe
$exe
done
done
是否有更干净或更快速的方法来执行此操作?除了 grep
和 find
之外,我还应该尝试其他命令吗?
I'm working with an embedded system running QNX that has a stripped-down shell (KSH).
I want to locate all run all executables on the filesystem that match the following:
*/shle/*-*_test
The "shle" directory may appear up to 4 levels deep under root. My current approach is to run the following commands:
for shle in ./shle ./*/shle ./*/*/shle ./*/*/*/shle
do
for exe in $shle/*-*_test
do
echo running: $exe
$exe
done
done
Is there a cleaner or faster way of doing this? Are there commands other than grep
and find
that I should try?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以尝试使用globstar选项并指定**/shle来查找一层或多层深度的目录。
来自 ksh 联机帮助页:
You could try using the globstar option and specifying **/shle to find the directories that are one or more levels deep.
From the ksh manpage:
如果您没有
find
,您就不能做得比您所做的更好了:枚举级别。如果您需要下降到任意级别,您可以使用递归函数来完成(但要注意,当您拥有的只是全局变量时,递归会很棘手)。幸运的是,有了已知的最大深度,事情就简单多了。还有一点改进的空间:最好在所有变量替换周围加上双引号,以防文件名中包含空格或特殊字符。并且您没有测试
$exe
是否存在且可执行(如果该模式不匹配任何内容,它可能是模式.../*-*_test
,或者可能它可能是一个不可执行的文件)。如果你甚至没有
test
(如果你有 ksh,它是内置的,但如果它是一个精简的 shell,它可能会丢失),你可能会通过更复杂的测试来逃脱看看模式是否已扩展:(我很惊讶你没有
find
,我以为 QNX 附带了完整的 POSIX 套件,但我不熟悉 QNX 生态系统,这可能是一个适用于小型设备的操作系统的精简版本。)If you don't have
find
, you can't do much better than what you did: enumerate the levels. If you needed to go down to arbitrary levels, you could do it with a recursive function (but watch out, recursion is tricky when all you have is global variables). Fortunately, with a known maximum depth, it's a lot simpler.There's a little room for improvement: you'd better put double quotes around all variable substitutions, in case there's a filename somewhere that contains whitespace or special characters. And you aren't testing whether
$exe
is exists and executable (it could be the pattern…/*-*_test
if that pattern doesn't match anything, or perhaps it could be a non-executable file).If you don't even have
test
(if you have ksh, it's built-in, but if it's a stripped-down shell it might be missing), you might get away with a more complicated test to see if the pattern was expanded:(I'm suprised that you don't have
find
, I thought QNX came with a full POSIX suite, but I'm unfamiliar with the QNX ecosystem, this could be a stripped-down version of the OS for a small device.)