Quantcast
Viewing all articles
Browse latest Browse all 21

bash pip-isms or right hand side of pipe variables

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.


Viewing all articles
Browse latest Browse all 21

Trending Articles