1

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.

1
  • 3
    You don't have to do anything special. The input will just appear on stdin as usual. Commented Oct 6, 2013 at 16:13

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.