首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何创建一个可以从标准输入读取的bash函数?

如何创建一个可以从标准输入读取的bash函数?
EN

Stack Overflow用户
提问于 2013-09-12 18:01:37
回答 3查看 89.1K关注 0票数 45

我有一些使用参数的脚本,它们工作得很好,但我希望它们能够从stdin中读取,例如,从管道中读取,例如,假设这称为read:

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

read $*

现在,这可以与read "foo" "bar"一起使用,但我想将其用作:

echo "foo" | read

我该如何做到这一点?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-09-12 18:04:42

您可以使用<<<来获得此行为。read <<< echo "text"应该能成功。

使用readly进行测试(我不喜欢使用保留字):

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

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

使用管道,基于this answer to "Bash script, read values from stdin pipe"

$ echo "hello bye" | { read a; echo $a;  echo "this was a test"; }
hello bye
this was a test
票数 39
EN

Stack Overflow用户

发布于 2015-05-30 01:02:25

下面是使用printf和标准输入的bash中sprintf函数的实现示例:

sprintf() { local stdin; read -d '' -u 0 stdin; printf "$@" "$stdin"; }

示例用法:

$ echo bar | sprintf "foo %s"
foo bar

这将使您了解函数如何从标准输入中读取。

票数 6
EN

Stack Overflow用户

发布于 2018-05-12 03:04:33

我发现使用testawk可以在一行内完成这项工作……

    test -p /dev/stdin  && awk '{print}' /dev/stdin

test -p测试管道上的输入,管道通过标准输入接受输入。只有当输入存在时,我们才想要运行awk,否则它将无限期地挂起,等待永远不会到来的输入。

我已经将其放入一个函数中,以使其易于使用。

inputStdin () {
  test -p /dev/stdin  && awk '{print}' /dev/stdin  && return 0
  ### accepts input if any but does not hang waiting for input
  #
  return 1
}

用法...

_stdin="$(inputStdin)"

另一个函数在没有测试的情况下使用awk等待命令行输入...

inputCli () {
  local _input=""
  local _prompt="$1"
  #
  [[ "$_prompt" ]]  && { printf "%s" "$_prompt" > /dev/tty; }
  ### no prompt at all if none supplied
  #
  _input="$(awk 'BEGIN {getline INPUT < "/dev/tty"; print INPUT}')"
  ### accept input (used in place of 'read')
  ###   put in a BEGIN section so will only accept 1 line and exit on ENTER
  ###   WAITS INDEFINITELY FOR INPUT
  #
  [[ "$_input" ]]  && { printf "%s" "$_input"; return 0; }
  #
  return 1
}

用法...

_userinput="$(inputCli "Prompt string: ")"

请注意,第一个printf上的> /dev/tty似乎是在命令替代$(...)中调用函数时打印提示所必需的。

这种awk的使用允许消除用于从键盘或标准输入收集输入的奇怪的read命令。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18761209

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档