[英]why pipe output into a bash function does not work
There are many discussions on this: Pipe output to bash function 关于此有许多讨论:将输出输出到bash函数
I just want to know why: 我只想知道为什么:
#bin/sh
function myfunc () {
echo $1
}
ls -la | myfunc
will give empty line. 将给空行。 May I ask that why isn't our output of
ls
not treated as $1
as the function? 请问为什么我们输出的
ls
不被视为$1
作为函数? What is the mechanism behind this? 其背后的机制是什么?
If we try: 如果我们尝试:
#bin/sh
function myfunc () {
i=${*:-$(</dev/stdin)}
echo $i
}
ls -la | myfunc
Then we have: 然后我们有:
total 32 drwxr-xr-x 6 phil staff 204 Sep 11 21:18 . drwx------+ 17 phil staff 578 Sep 10 21:34 .. lrwxr-xr-x 1 phil staff 2 Sep 10 21:35 s1 -> t1 lrwxr-xr-x 1 phil staff 2 Sep 10 21:35 s2 -> t2 lrwxr-xr-x 1 phil staff 2 Sep 10 21:35 s3 -> t3 -rwxr-xr-x 1 phil staff 96 Sep 11 21:39 test.sh
which does not keep the actual format of ls -la
(with \\n). 它不保留
ls -la
的实际格式(带有\\ n)。
What is the correct/proposed way to pass a command output to your function as a parameter as it is? 将命令输出原样作为参数传递给函数的正确/建议方法是什么?
Thanks 谢谢
Update +John Kugelman 更新+约翰·库格曼
#bin/sh
function myfunc () {
cat | grep "\->" | while read line
do
echo $line
done
cat | grep "\->" | while read line
do
echo "dummy"
done
}
ls -la | myfunc
This will only print once. 这只会打印一次。 What if we would like to use the result twice (store it as a variable possible?)
如果我们想两次使用结果(将其存储为变量)怎么办?
Thanks, 谢谢,
There are two different ways functions can receive input: 函数可以通过两种不同的方式接收输入:
$1
, $2
, etc. $1
, $2
等。 When you pipe output from one command to another, it's received on stdin, not as arguments. 当您将一个命令的输出通过管道传递给另一个命令时,它将在stdin上接收,而不是作为参数接收。 To read it you could do one of these:
要阅读它,您可以执行以下操作之一:
myfunc() {
cat
}
myfunc() {
local line
while IFS= read -r line; do
printf '%s\n' "$line"
done
}
ls -la | myfunc
If you want to leave your function as is and it expects $1
to be set, you'll need to change from a pipe to command substitution. 如果您希望按原样保留函数,并且希望设置
$1
,则需要从管道替换为命令替换。
myfunc() {
echo "$1"
}
myfunc "$(ls -la)"
Notice the abundant use of double quotes. 请注意大量使用双引号。 Make sure you write
echo "$1"
with quotes or else the newlines will be mangled. 确保您将
echo "$1"
用引号引起来,否则换行符将被修饰。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.