在bash脚本中的函数中读取stdin [英] read stdin in function in bash script

查看:120
本文介绍了在bash脚本中的函数中读取stdin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些bash函数集,可以输出一些信息:

I have some set of bash functions which output some information:

  • 在epson-ppds中找到型号名称
  • 在三星ppds中找到型号名称
  • 在hp-ppds中查找型号名称
  • 等...
  • find-modelname-in-epson-ppds
  • find-modelname-in-samsung-ppds
  • find-modelname-in-hp-ppds
  • etc ...

我一直在编写用于读取输出并对其进行过滤的函数:

I've been writing functions which read output and filter it:

function filter-epson {
    find-modelname-in-epson-ppds | sed <bla-blah-blah>
}

function filter-hp {
    find-modelname-in-hp-ppds | sed <the same bla-blah-blah>
}
etc ...

但是我认为这样做会更好:

But the I thought that it would be better do something like this:

function filter-general {
    (somehow get input) | sed <bla-blah-blah>
}

然后调用另一个高级函数:

and then call in another high-level functions:

function high-level-func {
    # outputs filtered information
    find-modelname-in-hp/epson/...-ppds | filter-general 
}

如何通过最佳的bash练习来实现?

How can I achieve that with the best bash practices?

推荐答案

如果问题是How do I pass stdin to a bash function?,则答案是:

If the question is How do I pass stdin to a bash function?, then the answer is:

Shellscript函数以普通方式使用stdin,就好像它们是命令或程序一样. :)

Shellscript functions take stdin the ordinary way, as if they were commands or programs. :)

input.txt:

input.txt:

HELLO WORLD
HELLO BOB
NO MATCH

test.sh:

#!/bin/sh

myfunction() {
    grep HELLO
}

cat input.txt | myfunction

输出:

hobbes@metalbaby:~/scratch$ ./test.sh 
 HELLO WORLD 
 HELLO BOB 

请注意,命令行参数也是以普通方式处理的,如下所示:

Note that command line arguments are ALSO handled in the ordinary way, like this:

test2.sh:

#!/bin/sh

myfunction() {
    grep "$1"
}

cat input.txt | myfunction BOB

输出:

hobbes@metalbaby:~/scratch/$ ./test2.sh 
 HELLO BOB 

这篇关于在bash脚本中的函数中读取stdin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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