简体   繁体   中英

In fish shell, why can't one function's output pipe to another?

Really hoping someone can help me to understand this behavior and how to work around it.

> functions hello
# Defined in ...
function hello
    echo -n $argv[1] "hello"
end
> functions world
# Defined in ...
function world
    echo -n "world"
end
> hello
hello⏎ 

> world
world⏎ 

> world | hello
hello⏎ 

You have misunderstood how the $argv function local variable is initialized. It is not set to the contents of stdin. It is set to the positional arguments of the function. For example, hello (world) will produce the output you expect. If you want your edit function to capture its data from stdin you need to explicitly read stdin.

As @Kurtis-Rader's answer mentioned, to access a pipe in a fish function, you use the read command (see man read ). This is similar to bash, sh, zsh, etc.

Example for fish (with edits discussed in the comments to make the piped input optional ):

function greeting
    echo "Good Morning"
end

function world
    if isatty stdin
        set greetstring "Hello"
    else
        read greetstring
    end
    echo (string trim $greetstring)", World"
end

> greeting | world
Good Morning, World

> world
Hello, World

To read multiline input from a pipe, you wrap the read in a while statement.

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