-
RSS Links
Categories
- /bike
- /blog
- /categoryless
- /coffee
- /dev/random
- /food
- /freenetworks
- /friends
- /funny
- /geek
- /GirTheCadillac
- /Lebowski
- /Life
- /LifeWithDog
- /me
- /metrix
- /music
- /National Wireless Summit 2006
- /phonecamera
- /photo
- /potpourri
- /seadrunks
- /seattle
- /seattlewireless
- /shmoocon
- /softball
- /StupidShellTricks
- /sysadmin
- /travel
- /unix
- /work
- cons
- monitoring
- pyramid
- ruby
Archives
- January 2011
- December 2010
- September 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- December 2008
- December 2007
- August 2007
- July 2007
- May 2007
- January 2007
- December 2006
- November 2006
- October 2006
- September 2006
- August 2006
- June 2006
- April 2006
- March 2006
- February 2006
- January 2006
- December 2005
- November 2005
- October 2005
- September 2005
- August 2005
- July 2005
- June 2005
- May 2005
- March 2005
- February 2005
- January 2005
- December 2004
- November 2004
- October 2004
- September 2004
- August 2004
- July 2004
- June 2004
- February 2004
- January 2004
- December 2003
- November 2003
- August 2003
Learn something new every day
Usually in a bash script when I want to parse a file line by line I do something like this:
exec < foo.txt
while read LINE;
do
SOMEVAR=$SOMEVAR,$LINE
done
This evening I was writing a bash wrapper for debootstrap to automate the building of chroot environments and for some reason I chose to stray away from my norm and did the following:
cat foo.txt | while read LINE;
do
SOMEVAR=$SOMEVAR,$LINE
done
After a few test runs I noticed
$SOMEVARdid not have what I expected after exiting the while loop. After some debugging (bash -x) I discovered the variable was magically empty after the lastread LINEof the while loop. I immediately went back to old ways of parsing and sure enough it worked as I expected. Hmm... Well after finding the explanation it makes perfect sense. I am just surprised I hadn't run into it before.From the Bash FAQ
E4) If I pipe the output of a command into `read variable', why doesn't
the output show up in $variable when the read command finishes?
This has to do with the parent-child relationship between Unix
processes. It affects all commands run in pipelines, not just
simple calls to `read'. For example, piping a command's output
into a `while' loop that repeatedly calls `read' will result in
the same behavior.
Each element of a pipeline runs in a separate process, a child of
the shell running the pipeline. A subprocess cannot affect its
parent's environment. When the `read' command sets the variable
to the input, that variable is set only in the subshell, not the
parent shell. When the subshell exits, the value of the variable
is lost.