Simon
Simon

Reputation: 2345

Write bash script that reads from pipe

I'd like to do something like that:

cat file.txt | ./myscript.sh

file.txt

http://google.com
http://amazon.com
...

How can I read data in myscript.sh?

Upvotes: 15

Views: 9010

Answers (3)

Gilles Quénot
Gilles Quénot

Reputation: 185015

You can do this with a while loop (process line by line), this is the usual way for this kind of things :

#!/bin/bash

while read a; do
    # something with "$a"
done

For further informations, see http://mywiki.wooledge.org/BashFAQ/001


If instead you'd like to slurp a whole file in a variable, try doing this :

#!/bin/bash

var="$(cat)"
echo "$var"

or

#!/bin/bash

var="$(</dev/stdin)"
echo "$var"

Upvotes: 16

ConcurrentHashMap
ConcurrentHashMap

Reputation: 5084

You could use something like this:

while read line; do
  echo $line;
done

Read further here: Bash script, read values from stdin pipe

Upvotes: 5

poitroae
poitroae

Reputation: 21367

You can trick read into accepting from a pipe like this:

echo "hello world" | { read test; echo test=$test; }

or even write a function like this:

read_from_pipe() { read "$@" <&0; }

Upvotes: 3

Related Questions