[Techtalk] weirdness piping to a variable
Miriam English
mim at miriam-english.org
Wed Sep 11 12:09:28 UTC 2013
Hi folks,
I was writing a little script today to automate something I was doing by
hand a lot. During the writing I needed to assign the result of a
sequence of piped commands to a variable. Normally I'd give the variable
name and assign it to the piped sequence of commands in backticks, but
that's always felt clumsy to me, especially if the chain of piped
commands was long. I occurred to me that it would be clearer if I could
take the output of a lot of commands I'd piped together and then pipe
the result into a variable. I couldn't think of a way to do this so
looked online and found something like this:
echo "quick brown fox" | cut -d' ' -f2 | ( read a ; echo $a )
It works, but it appears that I can only use "read" inside the
parenthesised part. I have no idea why. If I try to do it without the
parentheses like this:
echo "quick brown fox" | cut -d' ' -f2 | read a ; echo $a
nothing happens. I don't understand why.
As I understand it, the part inside parentheses is another process. I
can get variables into it, but unfortunately not out.
a="one" ; echo "two" | (read b ; echo "$a and $b") ; echo "$a and $b."
It's nice to be able to pipe values into a variable because it maintains
the left to right conceptual flow and makes it easier for me to
understand what I was doing when I come back much later, but it isn't
much help if I can't use the variables outside the parentheses.
Anybody have any ideas?
Cheers,
- Miriam
--
If you don't have any failures then you're not trying hard enough.
- Dr. Charles Elachi, director of NASA's Jet Propulsion Laboratory
-----
Website: http://miriam-english.org
Blogs: http://miriam-e.dreamwidth.org
http://miriam-e.livejournal.com
More information about the Techtalk
mailing list