如何在 xargs 中使用定义的函数

GMa*_*ter 33 bash xargs function

这是我的代码

#!/bin/bash

showword() {
  echo $1
}

echo This is a sample message | xargs -d' ' -t -n1 -P2 showword
Run Code Online (Sandbox Code Playgroud)

所以我有一个函数showword可以回显你作为参数传递给函数的任何字符串。

然后我xargs尝试调用该函数并将一个词一次传递给该函数,并并行运行该函数的 2 个副本。不起作用的是xargs无法识别该功能。我怎样才能实现我想要做的事情,我怎样才能让 xargs 与函数一起工作showword

cuo*_*glm 40

尝试导出函数,然后在子 shell 中调用它:

showword() {
  echo $1
}

export -f showword
echo This is a sample message | xargs -d' ' -t -n1 -P2 bash -c 'showword "$@"' _
Run Code Online (Sandbox Code Playgroud)

  • @FazleA。:阅读 http://unix.stackexchange.com/questions/152391/bash-c-with-positional-parameters (4认同)
  • 还有一个问题,为什么需要尾随_?是否阻止 xargs 处理其他任何事情? (3认同)
  • 当我执行导出 -f 时,我收到“导出:非法选项 -f” (2认同)
  • 为什么这样做?或者,更具体地说,为什么需要 bash -c 子shell(为什么 xargs 不能只检测和使用刚刚在同一个 shell 进程中定义的函数)? (2认同)