How To Piping into Functions

Bash can pipe data into functions.

There is one stdin for the whole script, and the function can read the data for this.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
function pipeMe1 {
    # Just read a line
    read var
    echo "One line read, it's :${var}"

    # More stdin can be left here, `read` more of it or cat the rest.
    # cat may hang if stdin is closed
}

function pipeMe2 {
    # Now read the rest of the stdin
    cat
}

function pipeMe3 {
    # Now read the rest of the stdin
    cat <<EOF
    Here is my heredoc
    $(cat)
    I've wrapped that stdin with more stdin
EOF
}

pipeMe1 <<EOF
line 1
line 2
EOF

pipeMe2 <<EOF
line 1
line 2
EOF

pipeMe3 <<EOF
line 1
line 2
EOF