如何使一个bash功能,可从标准输入读取? [英] How to make a bash function which can read from standard input?

查看:527
本文介绍了如何使一个bash功能,可从标准输入读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些脚本,带参数工作,他们的工作只是罚款,但我想他们能够从标准输入读取,例如一个管道,一个例子,假设这就是所谓的读:

I have some scripts that work with parameters, they work just fine but i would like them to be able to read from stdin, from a pipe for example, an example, suppose this is called read:

#!/bin/bash
function read()
{
 echo $*
}

read $*

现在这一点也适用读富,酒吧,但我想用它作为:

Now this works with read "foo" "bar", but I would like to use it as:

echo "foo" | read

我如何做到这一点?

How do I accomplish this?

推荐答案

您可以使用<<< 来获得这一行为。 阅读<<<回声文本应该做到这一点。

You can use <<< to get this behaviour. read <<< echo "text" should make it.

与测试 readly (I preFER不使用保留字):

Test with readly (I prefer not using reserved words):

function readly()
{
 echo $*
 echo "this was a test"
}

$ readly <<< echo "hello"
hello
this was a test

通过管道的基础上,这个答案为Bash脚本,从标准输入读取管道值

$ echo "hello bye" | { read a; echo $a;  echo "this was a test"; }
hello bye
this was a test

这篇关于如何使一个bash功能,可从标准输入读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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