用xargs调用shell函数 [英] Calling shell functions with xargs
问题描述
我正在尝试使用xargs并行调用一个更复杂的函数.
I am trying to use xargs to call a more complex function in parallel.
#!/bin/bash
echo_var(){
echo $1
return 0
}
seq -f "n%04g" 1 100 |xargs -n 1 -P 10 -i echo_var {}
exit 0
这将返回错误
xargs: echo_var: No such file or directory
任何有关如何使用xargs来完成此操作的想法,或者任何其他解决方案都将受到欢迎.
Any ideas on how I can use xargs to accomplish this, or any other solution(s) would be welcome.
推荐答案
导出函数应该做到这一点(未经测试):
Exporting the function should do it (untested):
export -f echo_var
seq -f "n%04g" 1 100 | xargs -n 1 -P 10 -I {} bash -c 'echo_var "$@"' _ {}
您可以使用内置的printf
代替外部的seq
:
You can use the builtin printf
instead of the external seq
:
printf "n%04g\n" {1..100} | xargs -n 1 -P 10 -I {} bash -c 'echo_var "$@"' _ {}
此外,像这样使用return 0
和exit 0
可以掩盖其前面的命令可能产生的任何错误值.另外,如果没有错误,则为默认设置,因此有些多余.
Also, using return 0
and exit 0
like that masks any error value that might be produced by the command preceding it. Also, if there's no error, it's the default and thus somewhat redundant.
@phobic提到可以将Bash命令 简化为
@phobic mentions that the Bash command could be simplified to
bash -c 'echo_var "{}"'
直接在其中移动{}
. 但是,如@Sasha所指出的,命令注入很容易.
moving the {}
directly inside it. But it's vulnerable to command injection as pointed out by @Sasha.
以下是您不应使用嵌入式格式的示例:
Here is an example why you should not use the embedded format:
$ echo '$(date)' | xargs -I {} bash -c 'echo_var "{}"'
Sun Aug 18 11:56:45 CDT 2019
为什么不的另一个示例:
echo '\"; date\"' | xargs -I {} bash -c 'echo_var "{}"'
这是使用安全格式输出的结果:
$ echo '$(date)' | xargs -I {} bash -c 'echo_var "$@"' _ {}
$(date)
This is comparable to using parameterized SQL queries to avoid injection.
我在命令替换中或在转义引号中使用date
,而不是Sasha注释中使用的rm
命令,因为它无损.
I'm using date
in a command substitution or in escaped quotes here instead of the rm
command used in Sasha's comment since it's non-destructive.
这篇关于用xargs调用shell函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!