在 fish shell 中,为什么一个函数的输出不能通过管道传递给另一个函数?
In fish shell, why can't one function's output pipe to another?
真心希望有人能帮助我理解这种行为以及如何解决它。
> 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⏎
您误解了 $argv
函数局部变量的初始化方式。它没有设置为标准输入的内容。它被设置为函数的位置参数。例如,hello (world)
将产生您期望的输出。如果您希望 edit
函数从标准输入捕获其数据,您需要显式读取标准输入。
如@Kurtis-Rader 的回答所述,要访问 fish 函数中的管道,您可以使用 read
命令(参见 man read
)。这类似于bash、sh、zsh等
fish 示例(评论中讨论了编辑以使管道输入 可选):
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
要从管道读取多行输入,请将 read
包装在 while
语句中。
真心希望有人能帮助我理解这种行为以及如何解决它。
> 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⏎
您误解了 $argv
函数局部变量的初始化方式。它没有设置为标准输入的内容。它被设置为函数的位置参数。例如,hello (world)
将产生您期望的输出。如果您希望 edit
函数从标准输入捕获其数据,您需要显式读取标准输入。
如@Kurtis-Rader 的回答所述,要访问 fish 函数中的管道,您可以使用 read
命令(参见 man read
)。这类似于bash、sh、zsh等
fish 示例(评论中讨论了编辑以使管道输入 可选):
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
要从管道读取多行输入,请将 read
包装在 while
语句中。