Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write bash script that reads from pipe

Tags:

bash

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?

like image 854
Simon Avatar asked Feb 11 '13 12:02

Simon


People also ask

Can you pipe in a bash script?

A pipe in Bash takes the standard output of one process and passes it as standard input into another process. Bash scripts support positional arguments that can be passed in at the command line.

What does || mean in shell script?

Just like && , || is a bash control operator: && means execute the statement which follows only if the preceding statement executed successfully (returned exit code zero). || means execute the statement which follows only if the preceding statement failed (returned a non-zero exit code).

What is $@ bash script?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.


1 Answers

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"
like image 177
Gilles Quenot Avatar answered Oct 22 '22 17:10

Gilles Quenot