[英]How can I search and execute two scripts simultaneously in Unix?
假设您有一个包含两个文件的文件夹。
示例: stop_tomcat_center.sh
和start_tomcat_center.sh
。
在我的示例中, ls *tomcat*
返回返回这两个脚本。 如何同时搜索和执行这两个脚本?
我试过了
ls *tomcat* | xargs sh
但仅执行第一个脚本(不执行第二个)。
一种并行执行多项操作的简单方法是使用GNU Parallel :
parallel ::: ./*tomcat*
或者,如果您的脚本第一行没有shebang:
parallel bash ::: ./*tomcat*
或者,如果您喜欢xargs
:
ls *tomcat* | xargs -P 2
xargs缺少-n 1
选项。
来自man xargs
:
-n max-args,--max-args = max-args
每个命令行最多使用max-args参数。 如果超出大小(请参阅-s选项),则使用少于max-args参数的参数,除非给出了-x选项,在这种情况下xargs将退出。
xargs否则尝试使用尽可能多的参数来执行命令,这对大多数命令都有意义。
在您的情况下ls *tomcat* | xargs sh
ls *tomcat* | xargs sh
正在运行sh stop_tomcat_center.sh start_tomcat_center.sh
,而stop_tomcat_center.sh可能只是忽略$1
参数。
同样,使用ls的输出也不是一个好主意。 更好的方法是使用find -maxdepth 1 -name '*tomcat*' -print0 | xargs -0 -n 1 sh
find -maxdepth 1 -name '*tomcat*' -print0 | xargs -0 -n 1 sh
或for command in *tomcat*; do sh "$command"; done
for command in *tomcat*; do sh "$command"; done
这个答案是基于这样的假设,即OP在“同时”编写时的意思是“同时具有一个命令行”。
对于并行执行的解决方案,请查看其他答案。
您可以执行以下搜索和执行
find . -name "*.sh" -exec sh x {} \;
find将找到文件,exec将找到匹配并执行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.