read stdin in function in bash script

浪子不回头ぞ 提交于 2019-11-30 04:14:31

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

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

input.txt:

HELLO WORLD
HELLO BOB
NO MATCH

test.sh:

#!/bin/sh

myfunction() {
    grep HELLO
}

cat input.txt | myfunction

Output:

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

Output:

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

To be painfully explicit that I'm piping from stdin, I sometimes write

cat - | ...

Call sed directly. That's it.

function filter-general {
    sed <bla-blah-blah>
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!