Linux tip 2 - read

October 22, 2009 by

bash’s built-in read may behave unexpectedly. I’m not sure exactly why, but it looks like it has to do with it expecting to be invoked in a loop. Here’s what I expected to work:

$ echo "thisisfirst thisissecond" | read first second
$ echo $first
$ echo $second

Wait, what? But I use read all the time for while loops like this:

cat file | while read col1 col2 col3; do
    printf "col1: %sncol2: %sncol3: %snn" $col1 $col2 $col3
done

and that has never let me down. So why can’t I do it this way? I don’t really know, do you? Here’s a work around:

echo "thisisfirst thisissecond" | while read first second; do
    #do junk here
done

Made by Adam for himself at addumb.com
:wq