bash脚本,读取标准输入管道值 [英] Bash script, read values from stdin pipe

查看:130
本文介绍了bash脚本,读取标准输入管道值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得的bash从该管道得到它标准输入处理数据,但没有运气,我的意思是没有的以下工作:

I am trying to get bash to process data from stdin that gets piped it, but no luck, what I mean is none of the following work:

echo "hello world" | test=($(< /dev/stdin)); echo test=$test
test=


echo "hello world" | read test; echo test=$test
test=


echo "hello world" | test=`cat`; echo test=$test
test=

我想要的输出为 =测试的hello world 。请注意,我试图把引号$测试,不能正常工作。

where I want the output to be test=hello world. Note I've tried putting "" quotes around "$test" that doesn't work either.

推荐答案

使用

IFS= read var << EOF
$(foo)
EOF

您的可以的伎俩成从管道接受这样的:

You can trick read into accepting from a pipe like this:

echo "hello world" | { read test; echo test=$test; }

甚至写这样的功能:

or even write a function like this:

read_from_pipe() { read "$@" <&0; }

但是,没有任何一点 - 你的变量赋值可能不会持续!一个管道可能产生一个子shell,那里的环境是按值继承,而不是引用。这就是为什么不从管道输入的麻烦 - 这是不确定的。

But there's no point - your variable assignments may not last! A pipeline may spawn a subshell, where the environment is inherited by value, not by reference. This is why read doesn't bother with input from a pipe - it's undefined.

仅供参考, http://www.etalabs.net/sh_tricks.html 是必要的克鲁夫特的一记漂亮的集合打怪异shell和Bourne shell的不兼容性,SH。

FYI, http://www.etalabs.net/sh_tricks.html is a nifty collection of the cruft necessary to fight the oddities and incompatibilities of bourne shells, sh.

这篇关于bash脚本,读取标准输入管道值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆