如何使一个bash函数可以从标准输入读取?

前端之家收集整理的这篇文章主要介绍了如何使一个bash函数可以从标准输入读取?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一些脚本使用的参数,他们工作很好,但我希望他们能够从stdin读取,从管道,例如,一个例子,假设这被称为读取:
  1. #!/bin/bash
  2. function read()
  3. {
  4. echo $*
  5. }
  6.  
  7. read $*

现在这个工作与读“foo”“酒吧”,但我想使用它作为:

  1. echo "foo" | read

如何完成这个?

您可以使用<<<得到这个行为。读取<<<回声“文本”应该。 用readly测试(我不喜欢使用保留字):
  1. function readly()
  2. {
  3. echo $*
  4. echo "this was a test"
  5. }
  6.  
  7. $ readly <<< echo "hello"
  8. hello
  9. this was a test

带管道,基于this answer to “Bash script,read values from stdin pipe”

  1. $ echo "hello bye" | { read a; echo $a; echo "this was a test"; }
  2. hello bye
  3. this was a test

猜你在找的Bash相关文章