简体   繁体   中英

How to use xargs with a function in fish shell?

I need to use xargs to call a function in parallel in fish shell. I tried this:

#!/bin/fish

function func
    echo $argv
end

echo 'example1' 'example2' | xargs -n1 func

But I got this:

xargs: func: No such file or directory

So, how can I make it work?

Using bash this worked:

#!/bin/bash

function func {
    echo $1
}
export -f func

echo 'example1' 'example2' | xargs -n1  bash -c 'func $@' _

The xargs command requires and external command. You can't give it a function. What you're trying to do won't work with bash, zsh, ksh, or any similar shell. The way to do this is put the function in a file named func that is in your PATH :

#!/bin/fish

function func
    echo $argv
end

func $argv

Now that it is implemented as an external command (a shell script) you can use it with xargs: echo 'example' | xargs func echo 'example' | xargs func .

Like Kurtis said, xargs won't work with functions. It can be made to work by launching another shell, but that's a hack.

What would probably work better for you is to not use xargs at all.

Instead of

echo 'example' | xargs func

just run func example .

In general, fish's command substitutions should be used for this.

So instead of

somecommand | xargs func

use

func (somecommand)

this will split somecommand s output on newlines, which is strictly speaking more strict than xargs (which will split on "blanks" and newline by default, but it will allow shell-like quoting and escaping), which is typically what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM