Accessing the output of a Bash pipe with 'read'

7

3

I'm trying to pipe some data from a Bash pipe into a Bash variable using the read command, like this:

$ echo "Alexander the Grape" | read quot
$ echo $quot
$ 

But quot is empty. Some Googling revealed that this is not a bug; it's an intended feature of Bash. (Section E5 in the FAQ.)

But when I tried the same thing in zsh, it worked. (Ditto for ksh.) Is there any way to make this work in Bash? I really don't want to have to type:

$ quot=$(echo "Alexander the Grape")

Especially for long commands.

Karthik

Posted 2010-08-08T02:39:13.313

Reputation: 95

Answers

3

For additional reading on this subject, see BashFAQ/024.

There are a bunch of ways to do variable assignments in Bash:

var=$(command)
read var <<< $(command)
read var <<< EOF
$(command)
EOF
printf -v var "%s" $(command)

etc.

Paused until further notice.

Posted 2010-08-08T02:39:13.313

Reputation: 86 075

Thanks. Not what I was looking for, but these are very interesting alternatives. – Karthik – 2010-08-10T03:03:34.773

0

I am guessing you are trying to create a command inside a variable and then run it by specifying the variable? Then don't. run the command as it is.

user31894

Posted 2010-08-08T02:39:13.313

Reputation: 2 245

Actually, I'm parsing really large numbers (1000+ digits). I wanted to store it into a variable because it got unwieldy after a while. – Karthik – 2010-08-10T02:27:28.027

0

Nope. If you prefer the behaviour of a different shell, switch to that shell. Market forces. :)

Phil P

Posted 2010-08-08T02:39:13.313

Reputation: 1 773

0

read quot < <(echo "Alexander the Grape")

Steven Penny

Posted 2010-08-08T02:39:13.313

Reputation: 7 294