tags:

views:

792

answers:

5

I'm trying to get bash to process data from stdin that gets piped it, but no luck, what I mean is none of the following work:

echo "hello world" | test=($(< /dev/stdin)); echo test=$test
test=


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


echo "hello world" | test=`cat`; echo test=$test
test=

where I want the output to be test=hello world. Note I've tried putting "" quotes around "$test" that doesn't work either.

+2  A: 

Piping something into an expression involving an assignment doesn't behave like that.

Instead, try:

test=$(echo "hello world"); echo test=$test
bta
+1  A: 

This what you want?

test=$(echo "Hello World")
echo $test
Rippy
+3  A: 

The syntax for an implicit pipe from a shell command into a bash variable is

var=$(command)

or

var=`command`

In your examples, you are piping data to an assignment statement, which does not expect any input.

mobrule
The first form, var=$(command), is preferable.
Kevin Little
+1  A: 

read won't read from a pipe (or possibly the result is lost because the pipe creates a subshell). You can, however, use a here string in Bash:

$ read a b c <<< $(echo 1 2 3)
$ echo $a $b $c
1 2 3
Dennis Williamson
A: 

if you want to read in lots of data and work on each line separately you could use something like this:

cat myFile | while read x ; do echo $x ; done

if you want to split the lines up into multiple words you can use multiple variables in place of x like this:

cat myFile | while read x y ; do echo $y $x ; done

alternatively:

while read x y ; do echo $y $x ; done < myFile

But as soon as you start to want to do anything really clever with this sort of thing you're better going for some scripting language like perl where you could try something like this:

perl -ane 'print "$F[0]\n"' < myFile

There's a fairly steep learning curve with perl (or I guess any of these languages) but you'll find it a lot easier in the long run if you want to do anything but the simplest of scripts. I'd recommend the Perl Cookbook and, of course, The Perl Programming Language by Larry Wall et al.

Nick