使用 xargs 调用 shell 函数 [英] Calling shell functions with xargs

查看:37
本文介绍了使用 xargs 调用 shell 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 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
" {1..100} | xargs -n 1 -P 10 -I {} bash -c 'echo_var "$@"' _ {}

此外,像这样使用 return 0exit 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)

这相当于使用参数化 SQL 查询以避免注射.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆