bash pip-isms or right hand side of pipe variables

| No Comments | No TrackBacks
Unlike my default shell (zsh), bash has a wonderful feature where it doesn't keep variables that are set at the other end of a pipe, so for example:
i=
cat foo | while read bar; do
    i=$bar
done
echo $i

Yields an empty line. I've been stung once or twice on this as I prototype the code initially in an interactive shell, which doesn't exhibit the issue.
The simplest solution is to use a named pipe.

i=
mkfifo /tmp/foo$$
cat foo >/tmp/foo$$&
pid=$!
while read bar; do
    i=$bar
done </tmp/foo$$

This gives the last line of the file in the i variable.

No TrackBacks

TrackBack URL: http://www.petesh.com/scgi-bin/MT/mt-tb.cgi/231

Leave a comment

About this Entry

This page contains a single entry by Pete Shanahan published on March 31, 2009 7:37 PM.

Lies my computer told me... (threads != processes) was the previous entry in this blog.

Classy error from XCode is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.