在xargs中使用用户定义的bash函数

lon*_*r21 10 bash xargs

我在.bashrc中有这个自定义函数:

function ord() {
  printf '%d' "'$1"
}
Run Code Online (Sandbox Code Playgroud)

如何让这个函数与xargs一起使用?:

cat anyFile.txt | awk '{split($0,a,""); for (i=1; i<=100; i++) print a[i]}' | xargs -i ord {}
xargs: ord: No such file or directory
Run Code Online (Sandbox Code Playgroud)

jor*_*anm 8

首先,你的函数只使用1个参数,所以在这里使用xargs只会占用第一个arg.您需要将功能更改为以下内容:

ord() {
   printf '%d' "$@"
}
Run Code Online (Sandbox Code Playgroud)

要让xargs使用bashrc中的函数,必须生成一个新的交互式shell.这样的事情可能有用:

awk '{split($0,a,""); for (i=1; i<=100; i++) print a[i]}' anyFile.txt | xargs bash -i -c 'ord $@' _
Run Code Online (Sandbox Code Playgroud)

由于您已经依赖于单词拆分,因此您可以将awk的输出存储在数组中.

arr=(awk '{split($0,a,""); for (i=1; i<=100; i++) print a[i]}' anyFile.txt)
ord "${arr[@]}"
Run Code Online (Sandbox Code Playgroud)

或者,你可以使用awk的printf:

awk '{split($0,a,""); for (i=1; i<=100; i++) printf("%d",a[i])}' anyFile.txt
Run Code Online (Sandbox Code Playgroud)

  • 或者你可以导出函数(`export -f`)和*not*使shell交互. (2认同)