首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用bash命令的奇怪行为

使用bash命令的奇怪行为
EN

Stack Overflow用户
提问于 2022-07-25 19:32:53
回答 1查看 37关注 0票数 0

下面是我的slowread.sh脚本:

代码语言:javascript
复制
#!/bin/bash
sleep 1
cat $1

现在查看这个find命令:

代码语言:javascript
复制
find /tmp/*.txt -exec slowread.sh {} \;

这个find命令工作得很好。它显示10个文件(因为我在/tmp中有10个/tmp文件)

现在看看这个find命令:

代码语言:javascript
复制
find /tmp/*.txt -exec slowread.sh {} +

使用"+“而不是"\;",find命令只显示第一个文件!我的问题是..。为什么?

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-25 19:43:32

来自手册页 of find

代码语言:javascript
复制
        -exec command {} +
              This variant of the -exec action runs the specified
              command on the selected files, but the command line is
              built by appending each selected file name at the end; the
              total number of invocations of the command will be much
              less than the number of matched files.  The command line
              is built in much the same way that xargs builds its
              command lines.  Only one instance of `{}' is allowed
              within the command, and it must appear at the end,
              immediately before the `+'; it needs to be escaped (with a
              `\') or quoted to protect it from interpretation by the
              shell.  The command is executed in the starting directory.
              If any invocation with the `+' form returns a non-zero
              value as exit status, then find returns a non-zero exit
              status.  If find encounters an error, this can sometimes
              cause an immediate exit, so some pending commands may not
              be run at all.  For this reason -exec my-
              command ... {} + -quit may not result in my-command
              actually being run.  This variant of -exec always returns
              true.

您的脚本调用cat $1,它输出第一个参数的内容,但第二个示例是使用多个参数一次调用脚本。其余的参数被忽略了,因为您的脚本根本没有引用它们。第一个示例之所以有效,是因为它每次调用时使用一个参数调用脚本10次。

如果您想支持find -exec {} +的情况,应该将脚本更改为运行cat "${@}",这将输出传递给脚本的所有参数的内容。

或者,如果您想在每个文件之间睡觉,可以在循环中处理它们:

代码语言:javascript
复制
#!/bin/bash
for arg ; do
  sleep 1
  cat "${arg}"
done
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73114474

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档