Haden Pike
Haden Pike

Reputation: 289

Read From Pipe in Bash Script

I've got a Bash script which is only ever going to be invoked via a pipe. I'm curious what's the best way to read the data from the pipe? The command will look like:

$ output_gen | process

My script is process. This is not homework, but it is a learning exercise.

Upvotes: 0

Views: 1401

Answers (2)

Ashik
Ashik

Reputation: 11

Method 1: You can use the ‘read command’ with a “while loop” to read from a pipe within a bash script.

#!/bin/sh
cat names.txt | while read name; do
echo "$name"
done

Method 2: You can use the ‘read command’ to read from a pipe within a script in the terminal. For example,

echo “Hello World!”  | { read name; echo “msg=$name”; }

Method 3: If you want to read a command through pipe, you need a script like this: func.sh:

#!/bin/bash
function read_stdin()
{
  cat > file.txt
}
read_stdin

This will take any command as input and redirect the output to file.txt. Try running:

date|./func.sh

Upvotes: 1

jordanm
jordanm

Reputation: 35014

When your program is receiving data from a pipeline, it's received via stdin. To read from stdin, use the read builtin. Here is an example:

myprog:

while read -r line; do 
    <something with "$line">
done

command:

printf 'foo\nbar\n' | ./myprog

Upvotes: 2

Related Questions