LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   read line doubt (https://www.linuxquestions.org/questions/linux-newbie-8/read-line-doubt-735539/)

vinaytp 06-25-2009 07:29 AM

read line doubt
 
hi all...

In the below script how the read line will come to know about the first line of the file entered as argument...

#!/bin/bash
file1=$1
while read line
do
echo $line
done < $file1

acid_kewpie 06-25-2009 08:18 AM

because on the last line, the file is being redirected into the loop upon which the while condition is dependent

David1357 06-25-2009 08:37 AM

Quote:

Originally Posted by vinaytp (Post 3585887)
In the below script, how will the "read line" come to know about the first line of the file entered as argument...

You can rewrite your script like this:
Code:

#!/bin/bash
file1=$1
while read line ; do echo $line ; done < $file1

When it is written this way, you can see that everything from "while" to "done" is really one command. This means that "< $file1" is fed into the command.

For more information, run "help while" at a command prompt:
Code:

[user@machine:~]:help while
while: while COMMANDS; do COMMANDS; done
    Expand and execute COMMANDS as long as the final command in the
    `while' COMMANDS has an exit status of zero.


i92guboj 06-25-2009 09:08 AM

I think that he's more concerned about the redirection.

The must-read for this is the 'REDIRECTION' section in the bash man page.

What happens with the < $file1 at the end of the loop is that that file is fed into it, becoming effectively stdin for all purposes in the context of the loop. read consumes it because it read from stdin, but it could be any other command. That's why in these cases you must be specially careful with what you put inside the loop as well.


All times are GMT -5. The time now is 10:14 AM.