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?

3 Answers 3

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

1 Comment

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'
5

You could use something like this:

while read line; do
  echo $line;
done

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

Comments

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; }

1 Comment

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.

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.