Twitter Updates

    follow me on Twitter

    G-AVLN in front of her home

    G-AVLN in front of her home

    Mostly Unix and Linux topics. But flying might get a mention too.

    Thursday, May 18, 2006

    Input redirection into a while loop

    I'm teaching shell scripting in Stamford this week. Earlier today we had a discussion about data redirection to/from various programming statements like if, while, etc.

    The offered approach was:

    while read -r
    do
    command(s)
    done 0< file

    One of the students asked if you could have the redirection specified before the while, i.e:

    0< file while read -r
    do
    command(s)
    done

    My immediate thought was - yes, it should work. I didn't offer my opinion at that point, though. Instead I answered the question with another one. I asked them if the following would work (my favourite example illustrating shell scan):

    $ 1> file < /etc/passwd cat 2> /dev/null

    I was truly convinced that the original question is another exhibition of the same behaviour, which allows to specify the I/O redirection at any (sensible) point of the command line.

    Well, whereas the cat command line above will work OK, the original construct does not work! I have tried various combinations, and deduced that any alias, function or external command can have redirection specified before the command itself. However, when you are dealing with reserved words (programming keywords) or built-ins, the mechanism is not recognised, with a "command not found" error message.

    Curious... Need to investigate it further, unless Clive comes back with an answer before then ;-)

    No comments:

    Blog Archive