15

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?

Simon
  • 2,329
  • 4
  • 30
  • 49

3 Answers3

16

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"
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • If your script simply holds a piece of a pipeline, e.g. a sed command, you can (after specifying the interpreter `#!/bin/bash`) just cat it: `cat|sed 's/abc/def/g'` – valid Mar 21 '13 at 17:31
5

You could use something like this:

while read line; do
  echo $line;
done

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

Community
  • 1
  • 1
ConcurrentHashMap
  • 4,998
  • 7
  • 44
  • 53
3

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; }
poitroae
  • 21,129
  • 10
  • 63
  • 81
  • This isn't "tricking" `read`. The problem is not reading from a pipe, it's that the variable that `read` sets is in a subshell, which goes away after the pipe completes. – chepner Feb 11 '13 at 14:13